source
stringlengths
3
92
c
stringlengths
26
2.25M
x_solve.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB SP code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" 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. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include "header.h" // Simplified threadprivate extracted from header.h //#pragma omp threadprivate(cv,rhon,lhs,lhsp,lhsm) // The live range on the array cv[] is iteration private for K and for J // loops because the first i loop writes in the whole array and the 2nd i // loop reads the whole array. cv[] is not used anywhere later. // The same with rhon[]. // cv[] and rhon[]should be privatized with ompen private(). If we care // only about tiling, then the TACO paper can ignore the fdeps and the code // can be tiles. To parallelize the code we need to privatize the two // arrays with private(). // lhs[][][] is iteration private for the loop k, it can be privatized with // private() also to enable parallelism. // For finding that the whole array is iteration private you need just to // the difference between source and sink for the k dimension and you'll // find it equanl to Zero so you conclude that the array is iteration // private for that dimension. // the fact that lhs[][][] is written in a loop and is read in the // following loop and that it is written in that loop and read in the // following loop makes the whole program in One SCC for the k dimension // (we have an sc graph for each loop dimension). // SCCs are described in details in the document // Desktop/stmt_clustering.txt // Full expansion of lhs[][][] will enable: // -- parallelization of the K outermost loop, // -- loop distribution, you can distribute the k loop and have one k loop that writes into // lhs[][][][] for all k values, then the second k loop will consume all // the values written by the first k loop. Loop distribution in this case // does not enhance things, it does not enable any advanced loop nest // transformation, so full expansion is not really very interesting. // So we just need privatization to the parallelization of the code. // // The arrays lhsp[][][] and lhsm[][][] are like lhs[][][], the are // iteration private to the k loop // // The array rhs[][][][] is the array in which this huge x_solve.c function puts the results. // The output of the huge K loop is stored in this array. It does not need // any privatization or exapansion. // In the original code, we had and irregular array accesses (look at the // loops by the end of the SCoP in the original SP): // i = grid_points[0]; // i1 = grid_points[0]; // lhs[j][i][*] = .... // lhs[j][i1][*] = ... // Since lhs[][][] is iteration private. The privatization will guarantee // that different iterations access different lines of lhs[][][] which // enable the parallelization of the loop although the original loop // contained an irregular write access. //--------------------------------------------------------------------- // this function performs the solution of the approximate factorization // step in the x-direction for all five matrix components // simultaneously. The Thomas algorithm is employed to solve the // systems for the x-lines. Boundary conditions are non-periodic //--------------------------------------------------------------------- void x_solve() { int i, j, k, i1, i2, m; double ru1, fac1, fac2; // #pragma omp parallel for default(shared) private(i,j,k,i1,i2,m, \ ru1,fac1,fac2) #pragma scop for (k = 1; k <= PROBLEM_SIZE - 2; k++) { // lhsinit(PROBLEM_SIZE - 2+1, ny2); // void lhsinit(int ni, int nj) { //--------------------------------------------------------------------- // zap the whole left hand side for starters // set all diagonal values to 1. This is overkill, but convenient //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (m = 0; m < 5; m++) { lhs [j][0][m] = 0.0; lhsp[j][0][m] = 0.0; lhsm[j][0][m] = 0.0; lhs [j][PROBLEM_SIZE - 2+1][m] = 0.0; lhsp[j][PROBLEM_SIZE - 2+1][m] = 0.0; lhsm[j][PROBLEM_SIZE - 2+1][m] = 0.0; } lhs [j][0][2] = 1.0; lhsp[j][0][2] = 1.0; lhsm[j][0][2] = 1.0; lhs [j][PROBLEM_SIZE - 2+1][2] = 1.0; lhsp[j][PROBLEM_SIZE - 2+1][2] = 1.0; lhsm[j][PROBLEM_SIZE - 2+1][2] = 1.0; } } //--------------------------------------------------------------------- // Computes the left hand side for the three x-factors //--------------------------------------------------------------------- //--------------------------------------------------------------------- // first fill the lhs for the u-eigenvalue //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (i = 0; i <= PROBLEM_SIZE-1; i++) { ru1 = c3c4*rho_i[k][j][i]; cv[i] = us[k][j][i]; rhon[i] = max(max(dx2+con43*ru1,dx5+c1c5*ru1), max(dxmax+ru1,dx1)); } for (i = 1; i <= PROBLEM_SIZE - 2; i++) { lhs[j][i][0] = 0.0; lhs[j][i][1] = -dttx2 * cv[i-1] - dttx1 * rhon[i-1]; lhs[j][i][2] = 1.0 + c2dttx1 * rhon[i]; lhs[j][i][3] = dttx2 * cv[i+1] - dttx1 * rhon[i+1]; lhs[j][i][4] = 0.0; } } //--------------------------------------------------------------------- // add fourth order dissipation //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { lhs[j][1][2] = lhs[j][1][2] + comz5; lhs[j][1][3] = lhs[j][1][3] - comz4; lhs[j][1][4] = lhs[j][1][4] + comz1; lhs[j][1+1][1] = lhs[j][1+1][1] - comz4; lhs[j][1+1][2] = lhs[j][1+1][2] + comz6; lhs[j][1+1][3] = lhs[j][1+1][3] - comz4; lhs[j][1+1][4] = lhs[j][1+1][4] + comz1; } for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (i = 3; i <= PROBLEM_SIZE-4; i++) { lhs[j][i][0] = lhs[j][i][0] + comz1; lhs[j][i][1] = lhs[j][i][1] - comz4; lhs[j][i][2] = lhs[j][i][2] + comz6; lhs[j][i][3] = lhs[j][i][3] - comz4; lhs[j][i][4] = lhs[j][i][4] + comz1; } } for (j = 1; j <= PROBLEM_SIZE - 2; j++) { lhs[j][ PROBLEM_SIZE-3][0] = lhs[j][ PROBLEM_SIZE-3][0] + comz1; lhs[j][ PROBLEM_SIZE-3][1] = lhs[j][ PROBLEM_SIZE-3][1] - comz4; lhs[j][ PROBLEM_SIZE-3][2] = lhs[j][ PROBLEM_SIZE-3][2] + comz6; lhs[j][ PROBLEM_SIZE-3][3] = lhs[j][ PROBLEM_SIZE-3][3] - comz4; lhs[j][ PROBLEM_SIZE-3+1][0] = lhs[j][ PROBLEM_SIZE-3+1][0] + comz1; lhs[j][ PROBLEM_SIZE-3+1][1] = lhs[j][ PROBLEM_SIZE-3+1][1] - comz4; lhs[j][ PROBLEM_SIZE-3+1][2] = lhs[j][ PROBLEM_SIZE-3+1][2] + comz5; } //--------------------------------------------------------------------- // subsequently, fill the other factors (u+c), (u-c) by adding to // the first //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (i = 1; i <= PROBLEM_SIZE - 2; i++) { lhsp[j][i][0] = lhs[j][i][0]; lhsp[j][i][1] = lhs[j][i][1] - dttx2 * speed[k][j][i-1]; lhsp[j][i][2] = lhs[j][i][2]; lhsp[j][i][3] = lhs[j][i][3] + dttx2 * speed[k][j][i+1]; lhsp[j][i][4] = lhs[j][i][4]; lhsm[j][i][0] = lhs[j][i][0]; lhsm[j][i][1] = lhs[j][i][1] + dttx2 * speed[k][j][i-1]; lhsm[j][i][2] = lhs[j][i][2]; lhsm[j][i][3] = lhs[j][i][3] - dttx2 * speed[k][j][i+1]; lhsm[j][i][4] = lhs[j][i][4]; } } //--------------------------------------------------------------------- // FORWARD ELIMINATION //--------------------------------------------------------------------- //--------------------------------------------------------------------- // perform the Thomas algorithm; first, FORWARD ELIMINATION //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (i = 0; i <= PROBLEM_SIZE-3; i++) { fac1 = 1.0/lhs[j][i][2]; lhs[j][i][3] = fac1*lhs[j][i][3]; lhs[j][i][4] = fac1*lhs[j][i][4]; for (m = 0; m < 3; m++) { rhs[k][j][i][m] = fac1*rhs[k][j][i][m]; } lhs[j][i+1][2] = lhs[j][i+1][2] - lhs[j][i+1][1]*lhs[j][i][3]; lhs[j][i+1][3] = lhs[j][i+1][3] - lhs[j][i+1][1]*lhs[j][i][4]; for (m = 0; m < 3; m++) { rhs[k][j][i+1][m] = rhs[k][j][i+1][m] - lhs[j][i+1][1]*rhs[k][j][i][m]; } lhs[j][i+2][1] = lhs[j][i+2][1] - lhs[j][i+2][0]*lhs[j][i][3]; lhs[j][i+2][2] = lhs[j][i+2][2] - lhs[j][i+2][0]*lhs[j][i][4]; for (m = 0; m < 3; m++) { rhs[k][j][i+2][m] = rhs[k][j][i+2][m] - lhs[j][i+2][0]*rhs[k][j][i][m]; } } } //--------------------------------------------------------------------- // The last two rows in this grid block are a bit different, // since they for (not have two more rows available for the // elimination of off-diagonal entries //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { fac1 = 1.0/lhs[j][PROBLEM_SIZE-2][2]; lhs[j][PROBLEM_SIZE-2][3] = fac1*lhs[j][PROBLEM_SIZE-2][3]; lhs[j][PROBLEM_SIZE-2][4] = fac1*lhs[j][PROBLEM_SIZE-2][4]; for (m = 0; m < 3; m++) { rhs[k][j][PROBLEM_SIZE-2][m] = fac1*rhs[k][j][PROBLEM_SIZE-2][m]; } lhs[j][PROBLEM_SIZE-1][2] = lhs[j][PROBLEM_SIZE-1][2] - lhs[j][PROBLEM_SIZE-1][1]*lhs[j][PROBLEM_SIZE-2][3]; lhs[j][PROBLEM_SIZE-1][3] = lhs[j][PROBLEM_SIZE-1][3] - lhs[j][PROBLEM_SIZE-1][1]*lhs[j][PROBLEM_SIZE-2][4]; for (m = 0; m < 3; m++) { rhs[k][j][PROBLEM_SIZE-1][m] = rhs[k][j][PROBLEM_SIZE-1][m] - lhs[j][PROBLEM_SIZE-1][1]*rhs[k][j][PROBLEM_SIZE-2][m]; } //--------------------------------------------------------------------- // scale the last row immediately //--------------------------------------------------------------------- fac2 = 1.0/lhs[j][PROBLEM_SIZE-1][2]; for (m = 0; m < 3; m++) { rhs[k][j][PROBLEM_SIZE-1][m] = fac2*rhs[k][j][PROBLEM_SIZE-1][m]; } } //--------------------------------------------------------------------- // for (the u+c and the u-c factors //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (i = 0; i <= PROBLEM_SIZE-3; i++) { fac1 = 1.0/lhsp[j][i][2]; lhsp[j][i][3] = fac1*lhsp[j][i][3]; lhsp[j][i][4] = fac1*lhsp[j][i][4]; rhs[k][j][i][3] = fac1*rhs[k][j][i][3]; lhsp[j][i+1][2] = lhsp[j][i+1][2] - lhsp[j][i+1][1]*lhsp[j][i][3]; lhsp[j][i+1][3] = lhsp[j][i+1][3] - lhsp[j][i+1][1]*lhsp[j][i][4]; rhs[k][j][i+1][3] = rhs[k][j][i+1][3] - lhsp[j][i+1][1]*rhs[k][j][i][3]; lhsp[j][i+2][1] = lhsp[j][i+2][1] - lhsp[j][i+2][0]*lhsp[j][i][3]; lhsp[j][i+2][2] = lhsp[j][i+2][2] - lhsp[j][i+2][0]*lhsp[j][i][4]; rhs[k][j][i+2][3] = rhs[k][j][i+2][3] - lhsp[j][i+2][0]*rhs[k][j][i][3]; fac1 = 1.0/lhsm[j][i][2]; lhsm[j][i][3] = fac1*lhsm[j][i][3]; lhsm[j][i][4] = fac1*lhsm[j][i][4]; rhs[k][j][i][4] = fac1*rhs[k][j][i][4]; lhsm[j][i+1][2] = lhsm[j][i+1][2] - lhsm[j][i+1][1]*lhsm[j][i][3]; lhsm[j][i+1][3] = lhsm[j][i+1][3] - lhsm[j][i+1][1]*lhsm[j][i][4]; rhs[k][j][i+1][4] = rhs[k][j][i+1][4] - lhsm[j][i+1][1]*rhs[k][j][i][4]; lhsm[j][i+2][1] = lhsm[j][i+2][1] - lhsm[j][i+2][0]*lhsm[j][i][3]; lhsm[j][i+2][2] = lhsm[j][i+2][2] - lhsm[j][i+2][0]*lhsm[j][i][4]; rhs[k][j][i+2][4] = rhs[k][j][i+2][4] - lhsm[j][i+2][0]*rhs[k][j][i][4]; } } //--------------------------------------------------------------------- // And again the last two rows separately //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { fac1 = 1.0/lhsp[j][PROBLEM_SIZE-2][2]; lhsp[j][PROBLEM_SIZE-2][3] = fac1*lhsp[j][PROBLEM_SIZE-2][3]; lhsp[j][PROBLEM_SIZE-2][4] = fac1*lhsp[j][PROBLEM_SIZE-2][4]; rhs[k][j][PROBLEM_SIZE-2][3] = fac1*rhs[k][j][PROBLEM_SIZE-2][3]; lhsp[j][PROBLEM_SIZE-1][2] = lhsp[j][PROBLEM_SIZE-1][2] - lhsp[j][PROBLEM_SIZE-1][1]*lhsp[j][PROBLEM_SIZE-2][3]; lhsp[j][PROBLEM_SIZE-1][3] = lhsp[j][PROBLEM_SIZE-1][3] - lhsp[j][PROBLEM_SIZE-1][1]*lhsp[j][PROBLEM_SIZE-2][4]; rhs[k][j][PROBLEM_SIZE-1][3] = rhs[k][j][PROBLEM_SIZE-1][3] - lhsp[j][PROBLEM_SIZE-1][1]*rhs[k][j][PROBLEM_SIZE-2][3]; fac1 = 1.0/lhsm[j][PROBLEM_SIZE-2][2]; lhsm[j][PROBLEM_SIZE-2][3] = fac1*lhsm[j][PROBLEM_SIZE-2][3]; lhsm[j][PROBLEM_SIZE-2][4] = fac1*lhsm[j][PROBLEM_SIZE-2][4]; rhs[k][j][PROBLEM_SIZE-2][4] = fac1*rhs[k][j][PROBLEM_SIZE-2][4]; lhsm[j][PROBLEM_SIZE-1][2] = lhsm[j][PROBLEM_SIZE-1][2] - lhsm[j][PROBLEM_SIZE-1][1]*lhsm[j][PROBLEM_SIZE-2][3]; lhsm[j][PROBLEM_SIZE-1][3] = lhsm[j][PROBLEM_SIZE-1][3] - lhsm[j][PROBLEM_SIZE-1][1]*lhsm[j][PROBLEM_SIZE-2][4]; rhs[k][j][PROBLEM_SIZE-1][4] = rhs[k][j][PROBLEM_SIZE-1][4] - lhsm[j][PROBLEM_SIZE-1][1]*rhs[k][j][PROBLEM_SIZE-2][4]; //--------------------------------------------------------------------- // Scale the last row immediately //--------------------------------------------------------------------- rhs[k][j][PROBLEM_SIZE-1][3] = rhs[k][j][PROBLEM_SIZE-1][3]/lhsp[j][PROBLEM_SIZE-1][2]; rhs[k][j][PROBLEM_SIZE-1][4] = rhs[k][j][PROBLEM_SIZE-1][4]/lhsm[j][PROBLEM_SIZE-1][2]; } //--------------------------------------------------------------------- // BACKSUBSTITUTION //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (m = 0; m < 3; m++) { rhs[k][j][PROBLEM_SIZE-2][m] = rhs[k][j][PROBLEM_SIZE-2][m] - lhs[j][PROBLEM_SIZE-2][3]*rhs[k][j][PROBLEM_SIZE-1][m]; } rhs[k][j][PROBLEM_SIZE-2][3] = rhs[k][j][PROBLEM_SIZE-2][3] - lhsp[j][PROBLEM_SIZE-2][3]*rhs[k][j][PROBLEM_SIZE-1][3]; rhs[k][j][PROBLEM_SIZE-2][4] = rhs[k][j][PROBLEM_SIZE-2][4] - lhsm[j][PROBLEM_SIZE-2][3]*rhs[k][j][PROBLEM_SIZE-1][4]; } //--------------------------------------------------------------------- // The first three factors //--------------------------------------------------------------------- for (j = 1; j <= PROBLEM_SIZE - 2; j++) { for (i = PROBLEM_SIZE-3; i >= 0; i--) { for (m = 0; m < 3; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[j][i][3]*rhs[k][j][i+1][m] - lhs[j][i][4]*rhs[k][j][i+2][m]; } //------------------------------------------------------------------- // And the remaining two //------------------------------------------------------------------- rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[j][i][3]*rhs[k][j][i+1][3] - lhsp[j][i][4]*rhs[k][j][i+2][3]; rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[j][i][3]*rhs[k][j][i+1][4] - lhsm[j][i][4]*rhs[k][j][i+2][4]; } } } #pragma endscop //--------------------------------------------------------------------- // Do the block-diagonal inversion //--------------------------------------------------------------------- ninvr(); }
density_prior_box_op.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <algorithm> #include <vector> #include "paddle/fluid/operators/detection/prior_box_op.h" namespace paddle { namespace operators { template <typename T> class DensityPriorBoxOpKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input = ctx.Input<paddle::framework::Tensor>("Input"); auto* image = ctx.Input<paddle::framework::Tensor>("Image"); auto* boxes = ctx.Output<paddle::framework::Tensor>("Boxes"); auto* vars = ctx.Output<paddle::framework::Tensor>("Variances"); auto variances = ctx.Attr<std::vector<float>>("variances"); auto clip = ctx.Attr<bool>("clip"); auto fixed_sizes = ctx.Attr<std::vector<float>>("fixed_sizes"); auto fixed_ratios = ctx.Attr<std::vector<float>>("fixed_ratios"); auto densities = ctx.Attr<std::vector<int>>("densities"); T step_w = static_cast<T>(ctx.Attr<float>("step_w")); T step_h = static_cast<T>(ctx.Attr<float>("step_h")); T offset = static_cast<T>(ctx.Attr<float>("offset")); auto img_width = image->dims()[3]; auto img_height = image->dims()[2]; auto feature_width = input->dims()[3]; auto feature_height = input->dims()[2]; T step_width, step_height; if (step_w == 0 || step_h == 0) { step_width = static_cast<T>(img_width) / feature_width; step_height = static_cast<T>(img_height) / feature_height; } else { step_width = step_w; step_height = step_h; } int num_priors = 0; #ifdef PADDLE_WITH_MKLML #pragma omp parallel for reduction(+ : num_priors) #endif for (size_t i = 0; i < densities.size(); ++i) { num_priors += (fixed_ratios.size()) * (pow(densities[i], 2)); } boxes->mutable_data<T>(ctx.GetPlace()); vars->mutable_data<T>(ctx.GetPlace()); auto box_dim = vars->dims(); boxes->Resize({feature_height, feature_width, num_priors, 4}); auto e_boxes = framework::EigenTensor<T, 4>::From(*boxes).setConstant(0.0); int step_average = static_cast<int>((step_width + step_height) * 0.5); std::vector<float> sqrt_fixed_ratios; #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (size_t i = 0; i < fixed_ratios.size(); i++) { sqrt_fixed_ratios.push_back(sqrt(fixed_ratios[i])); } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(2) #endif for (int h = 0; h < feature_height; ++h) { for (int w = 0; w < feature_width; ++w) { T center_x = (w + offset) * step_width; T center_y = (h + offset) * step_height; int idx = 0; // Generate density prior boxes with fixed sizes. for (size_t s = 0; s < fixed_sizes.size(); ++s) { auto fixed_size = fixed_sizes[s]; int density = densities[s]; int shift = step_average / density; // Generate density prior boxes with fixed ratios. for (size_t r = 0; r < fixed_ratios.size(); ++r) { float box_width_ratio = fixed_size * sqrt_fixed_ratios[r]; float box_height_ratio = fixed_size / sqrt_fixed_ratios[r]; float density_center_x = center_x - step_average / 2. + shift / 2.; float density_center_y = center_y - step_average / 2. + shift / 2.; for (int di = 0; di < density; ++di) { for (int dj = 0; dj < density; ++dj) { float center_x_temp = density_center_x + dj * shift; float center_y_temp = density_center_y + di * shift; e_boxes(h, w, idx, 0) = std::max( (center_x_temp - box_width_ratio / 2.) / img_width, 0.); e_boxes(h, w, idx, 1) = std::max( (center_y_temp - box_height_ratio / 2.) / img_height, 0.); e_boxes(h, w, idx, 2) = std::min( (center_x_temp + box_width_ratio / 2.) / img_width, 1.); e_boxes(h, w, idx, 3) = std::min( (center_y_temp + box_height_ratio / 2.) / img_height, 1.); idx++; } } } } } } if (clip) { T* dt = boxes->data<T>(); std::transform(dt, dt + boxes->numel(), dt, [](T v) -> T { return std::min<T>(std::max<T>(v, 0.), 1.); }); } framework::Tensor var_t; var_t.mutable_data<T>( phi::make_ddim({1, static_cast<int>(variances.size())}), ctx.GetPlace()); auto var_et = framework::EigenTensor<T, 2>::From(var_t); for (size_t i = 0; i < variances.size(); ++i) { var_et(0, i) = variances[i]; } int box_num = feature_height * feature_width * num_priors; auto var_dim = vars->dims(); vars->Resize({box_num, static_cast<int>(variances.size())}); auto e_vars = framework::EigenMatrix<T, Eigen::RowMajor>::From(*vars); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(2) #endif for (int i = 0; i < box_num; ++i) { for (size_t j = 0; j < variances.size(); ++j) { e_vars(i, j) = variances[j]; } } vars->Resize(var_dim); boxes->Resize(box_dim); } }; // namespace operators } // namespace operators } // namespace paddle
type_conversions.h
/* * This set of methods provides dataType conversions in all possible directions supported: * FP8, FP16, FLOAT, DOUBLE, INT8, UINT8, UINT16, * * @author raver119@gmail.com */ #ifndef LIBND4J_TYPE_CONVERSIONS_H #define LIBND4J_TYPE_CONVERSIONS_H #define ND4J_FLOAT8 0 #define ND4J_INT8 1 #define ND4J_UINT8 2 #define ND4J_FLOAT16 3 #define ND4J_INT16 4 #define ND4J_UINT16 5 #define ND4J_FLOAT32 6 #define ND4J_DOUBLE 7 #define ND4J_THRESHOLD 8 #define ND4J_FLOAT24 119 // not supported after all. might want to add support later. #include <ops/ops.h> #include <templatemath.h> #include <types/float16.h> #include <types/float8.h> #include <types/uint8.h> #include <types/int8.h> #include <types/int16.h> #include <types/uint16.h> typedef union { float f_; int i_; } FloatBits; #ifdef __CUDACC__ template<typename S, typename T> __device__ inline void convertKernelGeneric(void *dx, Nd4jIndex N, void *dz) { S *x = reinterpret_cast<S *> (dx); T *z = reinterpret_cast<T *> (dz); int tid = blockIdx.x * blockDim.x + threadIdx.x; for (Nd4jIndex i = tid; i < N; i+= blockDim.x * gridDim.x) { z[i] = (T) ((float) x[i]); } }; /* * PLEASE NOTE: This kernel doesn't allow loop for data. Basically: grid will be huge. */ template<typename T> __device__ inline void encoderKernelP1Generic(void *dx, Nd4jIndex N, void *dz, float threshold) { T *x = reinterpret_cast<T *> (dx); int *z = reinterpret_cast<int *> (dz); //basically, for phase One we want do calculation: how many eligible values we have, and which blocks will be holding data Nd4jIndex tid = blockIdx.x * blockDim.x + threadIdx.x; int pass = tid < N && nd4j::math::nd4j_abs<T>(x[tid]) >= (T) threshold ? 1 : 0; int bp=__syncthreads_count(pass); if (threadIdx.x == 0) { // saving out per-block passes z[blockIdx.x+1] = bp; // saving out sum atomicAdd(&z[0], bp); } } __device__ __inline__ int pow2i (int e){ return 1<<e; } #define NUM_BANKS 32 #define LOG_NUM_BANKS 4 // Define this to more rigorously avoid bank conflicts, even at the lower (root) levels of the tree //#define ZERO_BANK_CONFLICTS #ifdef ZERO_BANK_CONFLICTS #define CONFLICT_FREE_OFFSET(index) ((index) >> LOG_NUM_BANKS + (index) >> (2 * LOG_NUM_BANKS)) #else #define CONFLICT_FREE_OFFSET(index) ((index) >> LOG_NUM_BANKS) #endif #ifdef CHECK_BANK_CONFLICTS #define TEMP(index) CUT_BANK_CHECKER(temp, index) #else #define TEMP(index) temp[index] #endif inline bool isPowerOfTwo(int n) { return ((n&(n-1))==0) ; } inline int floorPow2(int n) { #ifdef WIN32 // method 2 return 1 << (int)logb((float)n); #else // method 1 // float nf = (float)n; // return 1 << (((*(int*)&nf) >> 23) - 127); int exp; frexp((float)n, &exp); return 1 << (exp - 1); #endif } template <bool isNP2> __device__ void loadSharedChunkFromMem(int *s_data, const int *g_idata, int n, int baseIndex, int& ai, int& bi, int& mem_ai, int& mem_bi, int& bankOffsetA, int& bankOffsetB) { int thid = threadIdx.x; mem_ai = baseIndex + threadIdx.x; mem_bi = mem_ai + blockDim.x; ai = thid; bi = thid + blockDim.x; // compute spacing to avoid bank conflicts bankOffsetA = CONFLICT_FREE_OFFSET(ai); bankOffsetB = CONFLICT_FREE_OFFSET(bi); // Cache the computational window in shared memory // pad values beyond n with zeros s_data[ai + bankOffsetA] = g_idata[mem_ai]; if (isNP2) { // compile-time decision s_data[bi + bankOffsetB] = (bi < n) ? g_idata[mem_bi] : 0; } else { s_data[bi + bankOffsetB] = g_idata[mem_bi]; } } template <bool isNP2> __device__ void storeSharedChunkToMem(int* g_odata, int* s_data, int n, int ai, int bi, int mem_ai, int mem_bi, int bankOffsetA, int bankOffsetB) { __syncthreads(); // write results to global memory g_odata[mem_ai] = s_data[ai + bankOffsetA]; if (isNP2) { // compile-time decision if (bi < n) g_odata[mem_bi] = s_data[bi + bankOffsetB]; } else { g_odata[mem_bi] = s_data[bi + bankOffsetB]; } } template <bool storeSum> __device__ void clearLastElement(int* s_data, int *g_blockSums, int blockIndex) { if (threadIdx.x == 0) { int index = (blockDim.x << 1) - 1; index += CONFLICT_FREE_OFFSET(index); if (storeSum) { // compile-time decision // write this block's total sum to the corresponding index in the blockSums array g_blockSums[blockIndex] = s_data[index]; } // zero the last element in the scan so it will propagate back to the front s_data[index] = 0; } } __device__ unsigned int buildSum(int *s_data) { unsigned int thid = threadIdx.x; unsigned int stride = 1; // build the sum in place up the tree for (int d = blockDim.x; d > 0; d >>= 1) { __syncthreads(); if (thid < d) { int i = __mul24(__mul24(2, stride), thid); int ai = i + stride - 1; int bi = ai + stride; ai += CONFLICT_FREE_OFFSET(ai); bi += CONFLICT_FREE_OFFSET(bi); s_data[bi] += s_data[ai]; } stride *= 2; } return stride; } __device__ void scanRootToLeaves(int *s_data, unsigned int stride) { unsigned int thid = threadIdx.x; // traverse down the tree building the scan in place for (int d = 1; d <= blockDim.x; d *= 2) { stride >>= 1; __syncthreads(); if (thid < d) { int i = __mul24(__mul24(2, stride), thid); int ai = i + stride - 1; int bi = ai + stride; ai += CONFLICT_FREE_OFFSET(ai); bi += CONFLICT_FREE_OFFSET(bi); float t = s_data[ai]; s_data[ai] = s_data[bi]; s_data[bi] += t; } } } template <bool storeSum> __device__ void prescanBlock(int *data, int blockIndex, int *blockSums) { int stride = buildSum(data); // build the sum in place up the tree clearLastElement<storeSum>(data, blockSums, (blockIndex == 0) ? blockIdx.x : blockIndex); scanRootToLeaves(data, stride); // traverse down tree to build the scan } template <bool storeSum, bool isNP2> __global__ void prescan(int *g_odata, const int *g_idata, int *g_blockSums, int n, int blockIndex, int baseIndex) { int ai, bi, mem_ai, mem_bi, bankOffsetA, bankOffsetB; extern __shared__ int s_data[]; // load data into shared memory loadSharedChunkFromMem<isNP2>((int *) s_data, g_idata, n, (baseIndex == 0) ? __mul24(blockIdx.x, (blockDim.x << 1)):baseIndex, ai, bi, mem_ai, mem_bi, bankOffsetA, bankOffsetB); // scan the data in each block prescanBlock<storeSum>(s_data, blockIndex, g_blockSums); // write results to device memory storeSharedChunkToMem<isNP2>(g_odata, s_data, n, ai, bi, mem_ai, mem_bi, bankOffsetA, bankOffsetB); } __global__ void uniformAdd(int *g_data, int *uniforms, int n, int blockOffset, int baseIndex) { __shared__ float uni; if (threadIdx.x == 0) uni = uniforms[blockIdx.x + blockOffset]; unsigned int address = __mul24(blockIdx.x, (blockDim.x << 1)) + baseIndex + threadIdx.x; __syncthreads(); // note two adds per thread g_data[address] += uni; g_data[address + blockDim.x] += (threadIdx.x + blockDim.x < n) * uni; } /* * This kernel does prefix sum in parallel, to calculate offsets for each block */ template<typename T> __device__ inline void encoderKernelP2Generic(void *dx, Nd4jIndex n, void *dz) { // TODO: to be remove } /* * PLEASE NOTE: This kernel doesn't allow loop for data. Basically: grid will be huge. * * Based on: https://github.com/knotman90/cuStreamComp <-- efficient CUDA stream compaction algorithm */ template<typename T> __device__ inline void encoderKernelP3Generic(void *dx, int *offsets, Nd4jIndex N, void *dz) { T *x = reinterpret_cast<T *> (dx); int *z = reinterpret_cast<int *> (dz); Nd4jIndex tid = blockIdx.x * blockDim.x + threadIdx.x; extern __shared__ int warpTotals[]; // fetch block offset only once __shared__ float threshold; __shared__ FloatBits fb; __shared__ int bo; __shared__ int limit; if (threadIdx.x == 0) { limit = z[0]; fb.i_ = z[2]; threshold = fb.f_; bo = offsets[blockIdx.x]; } __syncthreads(); if (tid < N) { T value = x[tid]; int pred = nd4j::math::nd4j_abs<T>(value) >= (T) threshold ? 1 : 0; int w_i = threadIdx.x/warpSize; //warp index int w_l = tid % warpSize;//thread index within a warp int t_m = INT_MAX >> (warpSize-w_l-1); //thread mask (ERROR IN THE PAPER minus one is required) int b = __ballot(pred) & t_m; //balres = number whose ith bit isone if the ith's thread pred is true masked up to the current index in warp int t_u = __popc(b); // popc count the number of bit one. simply count the number predicated true BEFORE MY INDEX if(w_l==warpSize-1){ warpTotals[w_i]=t_u+pred; } __syncthreads(); if(w_i==0 && w_l<blockDim.x/warpSize){ int w_i_u=0; for(int j=0;j<=5;j++){ int b_j =__ballot( warpTotals[w_l] & pow2i(j) ); //# of the ones in the j'th digit of the warp offsets w_i_u += (__popc(b_j & t_m) ) << j; //printf("indice %i t_m=%i,j=%i,b_j=%i,w_i_u=%i\n",w_l,t_m,j,b_j,w_i_u); } warpTotals[w_l]=w_i_u; } __syncthreads(); if(pred){ int idx = t_u + warpTotals[w_i] + bo + 4; if (idx < limit + 4) { z[idx]= value > (T) 0.0f ? tid+1 : -(tid + 1); x[tid] = value > (T) 0.0f ? x[tid] - threshold : x[tid] + threshold; } } } } /* * This kernel handles decode from sparse threshold array, to dense array * * PLEASE NOTE: Z is expected to be memset to 0 */ template<typename T> __device__ inline void decoderKernelGeneric(void *dx, Nd4jIndex N, void *dz) { int *x = reinterpret_cast<int *> (dx); T *z = reinterpret_cast<T *> (dz); int tid = blockIdx.x * blockDim.x + threadIdx.x; __shared__ float threshold; __shared__ int limit; __shared__ FloatBits fb; if (threadIdx.x == 0) { limit = x[0]; fb.i_ = x[2]; threshold = fb.f_; } __syncthreads(); for (int e = tid; e < limit; e += blockDim.x * gridDim.x) { int el = x[e+4]; int ael = nd4j::math::nd4j_abs<int>(el) - 1; // TODO: investigate, if += would work better here, as in "decoded accumulation" z[ael] += el > 0 ? threshold : -threshold; } } template<typename T> __device__ inline void cudaDecodeBitmapGeneric(void *dx, Nd4jIndex N, T *dz) { int tid = blockIdx.x * blockDim.x + threadIdx.x; __shared__ T *shmem; __shared__ FloatBits fb; __shared__ float threshold; __shared__ int *x; if (threadIdx.x == 0){ extern __shared__ char mem[]; shmem = (T*) mem; x = (int *)dx; fb.i_ = x[2]; threshold = fb.f_; } __syncthreads(); int lim = N / 16 + 5; for (int i = tid; i < N; i += blockDim.x * gridDim.x) { int byteId = i / 16 + 4; // printf("I: [%i]; byteId: [%i]\n", i, byteId); shmem[threadIdx.x] = dz[i]; __syncthreads(); if (threadIdx.x % 16 == 0) { int byte = x[byteId]; for (int e = 0; e < 16; e++) { if (i + e >= N) continue; int bitId = (i + e) % 16; bool hasBit = (byte & 1 << (bitId) ) != 0; bool hasSign = (byte & 1 << (bitId + 16) ) != 0; if (hasBit) { if (hasSign) shmem[threadIdx.x + bitId] -= threshold; else shmem[threadIdx.x + bitId] += threshold; } else if (hasSign) { shmem[threadIdx.x + bitId] -= threshold / 2; } } } __syncthreads(); dz[i] = shmem[threadIdx.x]; } } template<typename T> __device__ inline void cudaEncodeBitmapGeneric(T *dx, Nd4jIndex N, int *dz, int *scalar, int *reductionBuffer, float threshold) { int tid = blockIdx.x * blockDim.x + threadIdx.x; __shared__ int counter; __shared__ int *shmem; __shared__ T *vals; if (threadIdx.x == 0){ extern __shared__ char mem[]; shmem = (int*) mem; vals = (T *) (shmem + blockDim.x); counter = 0; } __syncthreads(); for (int i = tid; i < N; i += blockDim.x * gridDim.x) { // all threads in block reading stuff T val = dx[i]; T abs = nd4j::math::nd4j_abs<T>(val); int byteId = i / 16 + 4; int bitId = i % 16; shmem[threadIdx.x] = 0; vals[threadIdx.x] = val; if (abs >= (T) threshold) { shmem[threadIdx.x] = 1 << (bitId); atomicAdd(&counter, 1); if (val < (T) 0.0f) { shmem[threadIdx.x] |= 1 << (bitId + 16); vals[threadIdx.x] += (T) threshold; } else { vals[threadIdx.x] -= (T) threshold; } } else if (abs >= (T) threshold / (T) 2.0f && val < (T) 0.0f) { atomicAdd(&counter, 1); shmem[threadIdx.x] = 1 << (bitId + 16); vals[threadIdx.x] += (T) threshold / (T) 2.0f; } __syncthreads(); if (threadIdx.x % 16 == 0) { int byte = 0; for (int e = 0; e < 16; e++) { if (i + e >= N) continue; byte |= shmem[threadIdx.x + e]; } dz[byteId] = byte; } __syncthreads(); dx[i] = vals[threadIdx.x]; /* // but only 1 thread in sub-warp writes encoded values if (threadIdx.x % 16 == 0) { int byteId = i / 16 + 4; int byte = 0; for (int e = 0; e < 16; e++) { if (i + e >= N) continue; int bitId = (i + e) % 16; if (shmem[threadIdx.x + e + blockDim.x] >= (T) threshold) { byte |= 1 << (bitId + 1); atomicAdd(&counter, 1); if (shmem[threadIdx.x + e] < (T) 0.0f) { byte |= 1 << (bitId + 16 + 1); } shmem[threadIdx.x + e + blockDim.x] = (T) 0.0f; } else if (shmem[threadIdx.x + e + blockDim.x] >= (T) threshold / (T) 2.0f && shmem[threadIdx.x + e] < (T) 0.0f) { byte |= 1 << (bitId + 16 + 1); atomicAdd(&counter, 1); } } dz[byteId] = byte; } __syncthreads(); if (shmem[threadIdx.x + blockDim.x] == (T) 0.0f && shmem[threadIdx.x] != (T) 0.0f) { if (shmem[threadIdx.x] < (T) 0.0f) { dx[i] = shmem[threadIdx.x] + threshold; } else { dx[i] = shmem[threadIdx.x] - threshold; } } */ } __syncthreads(); if (threadIdx.x == 0) { atomicAdd(scalar, counter); } } extern "C" __global__ void cudaEncodeBitmapFloat(float *dx, Nd4jIndex N, int *dz, int *scalar, int *reductionBuffer, float threshold) { cudaEncodeBitmapGeneric<float>(dx, N, dz, scalar, reductionBuffer, threshold); } extern "C" __global__ void cudaEncodeBitmapDouble(double *dx, Nd4jIndex N, int *dz, int *scalar, int *reductionBuffer, float threshold) { cudaEncodeBitmapGeneric<double>(dx, N, dz, scalar, reductionBuffer, threshold); } extern "C" __global__ void cudaEncodeBitmapHalf(float16 *dx, Nd4jIndex N, int *dz, int *scalar, int *reductionBuffer, float threshold) { cudaEncodeBitmapGeneric<float16>(dx, N, dz, scalar, reductionBuffer, threshold); } extern "C" __global__ void cudaDecodeBitmapFloat(void *dx, Nd4jIndex N, float *dz) { cudaDecodeBitmapGeneric<float>(dx, N, dz); } extern "C" __global__ void cudaDecodeBitmapDouble(void *dx, Nd4jIndex N, double *dz) { cudaDecodeBitmapGeneric<double>(dx, N, dz); } extern "C" __global__ void cudaDecodeBitmapHalf(void *dx, Nd4jIndex N, float16 *dz) { cudaDecodeBitmapGeneric<float16>(dx, N, dz); } extern "C" __global__ void encoderKernelP1Float(void *dx, Nd4jIndex N, void *dz, float threshold) { encoderKernelP1Generic<float>(dx, N, dz, threshold); } extern "C" __global__ void encoderKernelP1Double(void *dx, Nd4jIndex N, void *dz, float threshold) { encoderKernelP1Generic<double>(dx, N, dz, threshold); } extern "C" __global__ void encoderKernelP1Half(void *dx, Nd4jIndex N, void *dz, float threshold) { encoderKernelP1Generic<float16>(dx, N, dz, threshold); } extern "C" __global__ void encoderKernelP2Float(int *dx, Nd4jIndex N, int *dz) { encoderKernelP2Generic<float>(dx, N, dz); } extern "C" __global__ void encoderKernelP3Float(void *dx, int *offsets, Nd4jIndex N, void *dz) { encoderKernelP3Generic<float>(dx, offsets, N, dz); } extern "C" __global__ void encoderKernelP3Double(void *dx, int *offsets, Nd4jIndex N, void *dz) { encoderKernelP3Generic<double>(dx, offsets, N, dz); } extern "C" __global__ void encoderKernelP3Half(void *dx, int *offsets, Nd4jIndex N, void *dz) { encoderKernelP3Generic<float16>(dx, offsets, N, dz); } extern "C" __global__ void decoderKernelFloat(void *dx, Nd4jIndex N, void *dz) { decoderKernelGeneric<float>(dx, N, dz); } extern "C" __global__ void decoderKernelDouble(void *dx, Nd4jIndex N, void *dz) { decoderKernelGeneric<double>(dx, N, dz); } extern "C" __global__ void decoderKernelHalf(void *dx, Nd4jIndex N, void *dz) { decoderKernelGeneric<float16>(dx, N, dz); } #endif template<typename S, typename T> void convertGeneric(void *dx, Nd4jIndex N, void *dz) { S *x = reinterpret_cast<S *> (dx); T *z = reinterpret_cast<T *> (dz); if (N < 8000) { #pragma omp simd for (int i = 0; i < N; i++) { z[i] = (T) ((float) x[i]); } } else { #pragma omp parallel for for (int i = 0; i < N; i++) { z[i] = (T) ((float) x[i]); } } }; template <typename T> void convertToThreshold(void *dx, Nd4jIndex N, void *dz) { // we suppose that first 4 bytes are integer, second 4 bytes are float // integer: enc length // integer: dec length // float: threshold FloatBits fb; T *x = (T *) dx; int *z = (int *) dz; int limit = z[0]; fb.i_ = z[2]; float threshold = fb.f_; // FIXME: int limit is sad thing here, 2B elements limitation z[1] = (int) N; // we use 3 as offset, since first 12 bytes are occupied with header int flimit = limit + 4; volatile int cnt = 4; volatile bool flag = false; #pragma omp parallel for schedule(guided) default(shared) for (int e = 0; e < N; e++) { bool flag_load; #pragma omp atomic read flag_load = flag; if (flag_load) continue; T cUpd = x[e]; if (cUpd >= (T) threshold) { int idx; #pragma omp atomic capture idx = cnt++; if (idx >= flimit) { #pragma omp atomic write flag = true; continue; } z[idx] = e + 1; x[e] -= (T) threshold; } else if (cUpd <= (T) -threshold) { int idx; #pragma omp atomic capture idx = cnt++; if (idx >= flimit) { #pragma omp atomic write flag = true; continue; } z[idx] = -e - 1; x[e] += (T) threshold; } } } template <typename T> void convertFromThreshold(void *dx, Nd4jIndex N, void *dz) { FloatBits fb; T *z = (T *) dz; int *x = (int *) dx; int limit = x[0]; fb.i_ = x[2]; float threshold = fb.f_; // we use 3 as offset, since first 12 bytes are occupied with header int flimit = limit + 4; #pragma omp parallel for schedule(guided) for (int e = 4; e < flimit; e++) { int el = x[e]; int ael = nd4j::math::nd4j_abs<int>(el) - 1; z[ael] += el > 0 ? threshold : -threshold; } } /* * TypeDef: * void convertTypes(Nd4jPointer *extras, int srcType, Nd4jPointer x, long N, int dstType, Nd4jPointer z); */ void NativeOps::convertTypes(Nd4jPointer *extras, int srcType, Nd4jPointer x, Nd4jIndex N, int dstType, Nd4jPointer z) { void *dx = reinterpret_cast<void *> (x); void *dz = reinterpret_cast<void *> (z); if (srcType == ND4J_FLOAT8) { if (dstType == ND4J_FLOAT8) { // convertGeneric<double, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { convertGeneric<nd4j::float8, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<nd4j::float8, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<nd4j::float8, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<nd4j::float8, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<nd4j::float8, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_FLOAT32) { convertGeneric<nd4j::float8, float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { convertGeneric<nd4j::float8, double>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_INT8) { if (dstType == ND4J_FLOAT8) { convertGeneric<nd4j::int8, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { //convertGeneric<nd4j::int8, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<nd4j::int8, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<nd4j::int8, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<nd4j::int8, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<nd4j::int8, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_FLOAT32) { convertGeneric<nd4j::int8, float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { convertGeneric<nd4j::int8, double>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_UINT8) { if (dstType == ND4J_FLOAT8) { convertGeneric<nd4j::uint8, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { convertGeneric<nd4j::uint8, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<nd4j::uint8, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<nd4j::uint8, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<nd4j::uint8, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<nd4j::uint8, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_FLOAT32) { convertGeneric<nd4j::uint8, float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { convertGeneric<nd4j::uint8, double>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_FLOAT16) { if (dstType == ND4J_FLOAT8) { convertGeneric<float16, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { convertGeneric<float16, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<float16, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<float16, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<float16, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<float16, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_FLOAT32) { convertGeneric<float16, float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { convertGeneric<float16, double>(dx, N, dz); } else if (dstType == ND4J_THRESHOLD) { convertToThreshold<float16>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_INT16) { if (dstType == ND4J_FLOAT8) { convertGeneric<nd4j::int16, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { convertGeneric<nd4j::int16, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<nd4j::int16, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<nd4j::int16, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<nd4j::int16, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<nd4j::int16, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_FLOAT32) { convertGeneric<nd4j::int16, float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { convertGeneric<nd4j::int16, double>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_FLOAT24) { } else if (srcType == ND4J_FLOAT32) { if (dstType == ND4J_FLOAT8) { convertGeneric<float, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { convertGeneric<float, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<float, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<float, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<float, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<float, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_DOUBLE) { convertGeneric<float, double>(dx, N, dz); } else if (dstType == ND4J_THRESHOLD) { convertToThreshold<float>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_DOUBLE) { if (dstType == ND4J_FLOAT8) { convertGeneric<double, nd4j::float8>(dx, N, dz); } else if (dstType == ND4J_INT8) { convertGeneric<double, nd4j::int8>(dx, N, dz); } else if (dstType == ND4J_UINT8) { convertGeneric<double, nd4j::uint8>(dx, N, dz); } else if (dstType == ND4J_FLOAT16) { convertGeneric<double, float16>(dx, N, dz); } else if (dstType == ND4J_INT16) { convertGeneric<double, nd4j::int16>(dx, N, dz); } else if (dstType == ND4J_UINT16) { convertGeneric<double, nd4j::uint16>(dx, N, dz); } else if (dstType == ND4J_FLOAT24) { } else if (dstType == ND4J_FLOAT32) { convertGeneric<double, float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { // } else if (dstType == ND4J_THRESHOLD) { convertToThreshold<double>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else if (srcType == ND4J_THRESHOLD) { if (dstType == ND4J_FLOAT16) { convertFromThreshold<float16>(dx, N, dz); } else if (dstType == ND4J_FLOAT32) { convertFromThreshold<float>(dx, N, dz); } else if (dstType == ND4J_DOUBLE) { convertFromThreshold<double>(dx, N, dz); } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } else { printf("Unsupported types conversion: [%i] -> [%i]\n", srcType, dstType); } } #endif //LIBND4J_TYPE_CONVERSIONS_H
irbuilder_nested_parallel_for.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -x c++ -emit-llvm %s -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -o - | FileCheck --check-prefixes=CHECK %s // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -debug-info-kind=limited -std=c++11 -verify %s -emit-llvm -o - | FileCheck --check-prefixes=CHECK-DEBUG %s // expected-no-diagnostics // TODO: Teach the update script to check new functions too. #ifndef HEADER #define HEADER // CHECK-LABEL: @_Z14parallel_for_0v( // CHECK-NEXT: entry: // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]) // CHECK-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK: omp_parallel: // CHECK-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* @_Z14parallel_for_0v..omp_par to void (i32*, i32*, ...)*)) // CHECK-NEXT: br label [[OMP_PAR_OUTLINED_EXIT:%.*]] // CHECK: omp.par.outlined.exit: // CHECK-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK: omp.par.exit.split: // CHECK-NEXT: ret void // // CHECK-DEBUG-LABEL: @_Z14parallel_for_0v( // CHECK-DEBUG-NEXT: entry: // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]), !dbg [[DBG13:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK-DEBUG: omp_parallel: // CHECK-DEBUG-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* @_Z14parallel_for_0v..omp_par to void (i32*, i32*, ...)*)), !dbg [[DBG14:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PAR_OUTLINED_EXIT:%.*]] // CHECK-DEBUG: omp.par.outlined.exit: // CHECK-DEBUG-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK-DEBUG: omp.par.exit.split: // CHECK-DEBUG-NEXT: ret void, !dbg [[DBG18:![0-9]+]] // void parallel_for_0(void) { #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) { } } } // CHECK-LABEL: @_Z14parallel_for_1Pfid( // CHECK-NEXT: entry: // CHECK-NEXT: [[STRUCTARG17:%.*]] = alloca { i32*, double*, float** }, align 8 // CHECK-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK: omp_parallel: // CHECK-NEXT: [[GEP_A_ADDR18:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG17]], i32 0, i32 0 // CHECK-NEXT: store i32* [[A_ADDR]], i32** [[GEP_A_ADDR18]], align 8 // CHECK-NEXT: [[GEP_B_ADDR19:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG17]], i32 0, i32 1 // CHECK-NEXT: store double* [[B_ADDR]], double** [[GEP_B_ADDR19]], align 8 // CHECK-NEXT: [[GEP_R_ADDR20:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG17]], i32 0, i32 2 // CHECK-NEXT: store float** [[R_ADDR]], float*** [[GEP_R_ADDR20]], align 8 // CHECK-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, { i32*, double*, float** }*)* @_Z14parallel_for_1Pfid..omp_par.4 to void (i32*, i32*, ...)*), { i32*, double*, float** }* [[STRUCTARG17]]) // CHECK-NEXT: br label [[OMP_PAR_OUTLINED_EXIT16:%.*]] // CHECK: omp.par.outlined.exit16: // CHECK-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK: omp.par.exit.split: // CHECK-NEXT: ret void // // CHECK-DEBUG-LABEL: @_Z14parallel_for_1Pfid( // CHECK-DEBUG-NEXT: entry: // CHECK-DEBUG-NEXT: [[STRUCTARG17:%.*]] = alloca { i32*, double*, float** }, align 8 // CHECK-DEBUG-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-DEBUG-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-DEBUG-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata float** [[R_ADDR]], metadata [[META72:![0-9]+]], metadata !DIExpression()), !dbg [[DBG73:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata i32* [[A_ADDR]], metadata [[META74:![0-9]+]], metadata !DIExpression()), !dbg [[DBG75:![0-9]+]] // CHECK-DEBUG-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata double* [[B_ADDR]], metadata [[META76:![0-9]+]], metadata !DIExpression()), !dbg [[DBG77:![0-9]+]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB6:[0-9]+]]), !dbg [[DBG78:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK-DEBUG: omp_parallel: // CHECK-DEBUG-NEXT: [[GEP_A_ADDR18:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG17]], i32 0, i32 0 // CHECK-DEBUG-NEXT: store i32* [[A_ADDR]], i32** [[GEP_A_ADDR18]], align 8 // CHECK-DEBUG-NEXT: [[GEP_B_ADDR19:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG17]], i32 0, i32 1 // CHECK-DEBUG-NEXT: store double* [[B_ADDR]], double** [[GEP_B_ADDR19]], align 8 // CHECK-DEBUG-NEXT: [[GEP_R_ADDR20:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG17]], i32 0, i32 2 // CHECK-DEBUG-NEXT: store float** [[R_ADDR]], float*** [[GEP_R_ADDR20]], align 8 // CHECK-DEBUG-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB6]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, { i32*, double*, float** }*)* @_Z14parallel_for_1Pfid..omp_par.4 to void (i32*, i32*, ...)*), { i32*, double*, float** }* [[STRUCTARG17]]), !dbg [[DBG79:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PAR_OUTLINED_EXIT16:%.*]] // CHECK-DEBUG: omp.par.outlined.exit16: // CHECK-DEBUG-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK-DEBUG: omp.par.exit.split: // CHECK-DEBUG-NEXT: ret void, !dbg [[DBG81:![0-9]+]] // void parallel_for_1(float *r, int a, double b) { #pragma omp parallel { #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) { *r = a + b; } } } } // CHECK-LABEL: @_Z14parallel_for_2Pfid( // CHECK-NEXT: entry: // CHECK-NEXT: [[STRUCTARG:%.*]] = alloca { i32*, double*, float** }, align 8 // CHECK-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-NEXT: [[I185:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[AGG_CAPTURED186:%.*]] = alloca [[STRUCT_ANON_17:%.*]], align 8 // CHECK-NEXT: [[AGG_CAPTURED187:%.*]] = alloca [[STRUCT_ANON_18:%.*]], align 4 // CHECK-NEXT: [[DOTCOUNT_ADDR188:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_LASTITER203:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_LOWERBOUND204:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_UPPERBOUND205:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[P_STRIDE206:%.*]] = alloca i32, align 4 // CHECK-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK: omp_parallel: // CHECK-NEXT: [[GEP_A_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 0 // CHECK-NEXT: store i32* [[A_ADDR]], i32** [[GEP_A_ADDR]], align 8 // CHECK-NEXT: [[GEP_B_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 1 // CHECK-NEXT: store double* [[B_ADDR]], double** [[GEP_B_ADDR]], align 8 // CHECK-NEXT: [[GEP_R_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 2 // CHECK-NEXT: store float** [[R_ADDR]], float*** [[GEP_R_ADDR]], align 8 // CHECK-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, { i32*, double*, float** }*)* @_Z14parallel_for_2Pfid..omp_par.23 to void (i32*, i32*, ...)*), { i32*, double*, float** }* [[STRUCTARG]]) // CHECK-NEXT: br label [[OMP_PAR_OUTLINED_EXIT184:%.*]] // CHECK: omp.par.outlined.exit184: // CHECK-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK: omp.par.exit.split: // CHECK-NEXT: store i32 0, i32* [[I185]], align 4 // CHECK-NEXT: [[TMP0:%.*]] = getelementptr inbounds [[STRUCT_ANON_17]], %struct.anon.17* [[AGG_CAPTURED186]], i32 0, i32 0 // CHECK-NEXT: store i32* [[I185]], i32** [[TMP0]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = getelementptr inbounds [[STRUCT_ANON_18]], %struct.anon.18* [[AGG_CAPTURED187]], i32 0, i32 0 // CHECK-NEXT: [[TMP2:%.*]] = load i32, i32* [[I185]], align 4 // CHECK-NEXT: store i32 [[TMP2]], i32* [[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt.19(i32* [[DOTCOUNT_ADDR188]], %struct.anon.17* [[AGG_CAPTURED186]]) // CHECK-NEXT: [[DOTCOUNT189:%.*]] = load i32, i32* [[DOTCOUNT_ADDR188]], align 4 // CHECK-NEXT: br label [[OMP_LOOP_PREHEADER190:%.*]] // CHECK: omp_loop.preheader190: // CHECK-NEXT: store i32 0, i32* [[P_LOWERBOUND204]], align 4 // CHECK-NEXT: [[TMP3:%.*]] = sub i32 [[DOTCOUNT189]], 1 // CHECK-NEXT: store i32 [[TMP3]], i32* [[P_UPPERBOUND205]], align 4 // CHECK-NEXT: store i32 1, i32* [[P_STRIDE206]], align 4 // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM207:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @[[GLOB1]], i32 [[OMP_GLOBAL_THREAD_NUM207]], i32 34, i32* [[P_LASTITER203]], i32* [[P_LOWERBOUND204]], i32* [[P_UPPERBOUND205]], i32* [[P_STRIDE206]], i32 1, i32 0) // CHECK-NEXT: [[TMP4:%.*]] = load i32, i32* [[P_LOWERBOUND204]], align 4 // CHECK-NEXT: [[TMP5:%.*]] = load i32, i32* [[P_UPPERBOUND205]], align 4 // CHECK-NEXT: [[TMP6:%.*]] = sub i32 [[TMP5]], [[TMP4]] // CHECK-NEXT: [[TMP7:%.*]] = add i32 [[TMP6]], 1 // CHECK-NEXT: br label [[OMP_LOOP_HEADER191:%.*]] // CHECK: omp_loop.header191: // CHECK-NEXT: [[OMP_LOOP_IV197:%.*]] = phi i32 [ 0, [[OMP_LOOP_PREHEADER190]] ], [ [[OMP_LOOP_NEXT199:%.*]], [[OMP_LOOP_INC194:%.*]] ] // CHECK-NEXT: br label [[OMP_LOOP_COND192:%.*]] // CHECK: omp_loop.cond192: // CHECK-NEXT: [[OMP_LOOP_CMP198:%.*]] = icmp ult i32 [[OMP_LOOP_IV197]], [[TMP7]] // CHECK-NEXT: br i1 [[OMP_LOOP_CMP198]], label [[OMP_LOOP_BODY193:%.*]], label [[OMP_LOOP_EXIT195:%.*]] // CHECK: omp_loop.body193: // CHECK-NEXT: [[TMP8:%.*]] = add i32 [[OMP_LOOP_IV197]], [[TMP4]] // CHECK-NEXT: call void @__captured_stmt.20(i32* [[I185]], i32 [[TMP8]], %struct.anon.18* [[AGG_CAPTURED187]]) // CHECK-NEXT: [[TMP9:%.*]] = load i32, i32* [[A_ADDR]], align 4 // CHECK-NEXT: [[CONV200:%.*]] = sitofp i32 [[TMP9]] to double // CHECK-NEXT: [[TMP10:%.*]] = load double, double* [[B_ADDR]], align 8 // CHECK-NEXT: [[ADD201:%.*]] = fadd double [[CONV200]], [[TMP10]] // CHECK-NEXT: [[CONV202:%.*]] = fptrunc double [[ADD201]] to float // CHECK-NEXT: [[TMP11:%.*]] = load float*, float** [[R_ADDR]], align 8 // CHECK-NEXT: store float [[CONV202]], float* [[TMP11]], align 4 // CHECK-NEXT: br label [[OMP_LOOP_INC194]] // CHECK: omp_loop.inc194: // CHECK-NEXT: [[OMP_LOOP_NEXT199]] = add nuw i32 [[OMP_LOOP_IV197]], 1 // CHECK-NEXT: br label [[OMP_LOOP_HEADER191]] // CHECK: omp_loop.exit195: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB1]], i32 [[OMP_GLOBAL_THREAD_NUM207]]) // CHECK-NEXT: [[OMP_GLOBAL_THREAD_NUM208:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @[[GLOB2:[0-9]+]], i32 [[OMP_GLOBAL_THREAD_NUM208]]) // CHECK-NEXT: br label [[OMP_LOOP_AFTER196:%.*]] // CHECK: omp_loop.after196: // CHECK-NEXT: ret void // // CHECK-DEBUG-LABEL: @_Z14parallel_for_2Pfid( // CHECK-DEBUG-NEXT: entry: // CHECK-DEBUG-NEXT: [[STRUCTARG:%.*]] = alloca { i32*, double*, float** }, align 8 // CHECK-DEBUG-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // CHECK-DEBUG-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // CHECK-DEBUG-NEXT: [[I185:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[AGG_CAPTURED186:%.*]] = alloca [[STRUCT_ANON_17:%.*]], align 8 // CHECK-DEBUG-NEXT: [[AGG_CAPTURED187:%.*]] = alloca [[STRUCT_ANON_18:%.*]], align 4 // CHECK-DEBUG-NEXT: [[DOTCOUNT_ADDR188:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_LASTITER203:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_LOWERBOUND204:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_UPPERBOUND205:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: [[P_STRIDE206:%.*]] = alloca i32, align 4 // CHECK-DEBUG-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata float** [[R_ADDR]], metadata [[META133:![0-9]+]], metadata !DIExpression()), !dbg [[DBG134:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata i32* [[A_ADDR]], metadata [[META135:![0-9]+]], metadata !DIExpression()), !dbg [[DBG136:![0-9]+]] // CHECK-DEBUG-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata double* [[B_ADDR]], metadata [[META137:![0-9]+]], metadata !DIExpression()), !dbg [[DBG138:![0-9]+]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB13:[0-9]+]]), !dbg [[DBG139:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PARALLEL:%.*]] // CHECK-DEBUG: omp_parallel: // CHECK-DEBUG-NEXT: [[GEP_A_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 0 // CHECK-DEBUG-NEXT: store i32* [[A_ADDR]], i32** [[GEP_A_ADDR]], align 8 // CHECK-DEBUG-NEXT: [[GEP_B_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 1 // CHECK-DEBUG-NEXT: store double* [[B_ADDR]], double** [[GEP_B_ADDR]], align 8 // CHECK-DEBUG-NEXT: [[GEP_R_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 2 // CHECK-DEBUG-NEXT: store float** [[R_ADDR]], float*** [[GEP_R_ADDR]], align 8 // CHECK-DEBUG-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB13]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, { i32*, double*, float** }*)* @_Z14parallel_for_2Pfid..omp_par.23 to void (i32*, i32*, ...)*), { i32*, double*, float** }* [[STRUCTARG]]), !dbg [[DBG140:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_PAR_OUTLINED_EXIT184:%.*]] // CHECK-DEBUG: omp.par.outlined.exit184: // CHECK-DEBUG-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // CHECK-DEBUG: omp.par.exit.split: // CHECK-DEBUG-NEXT: call void @llvm.dbg.declare(metadata i32* [[I185]], metadata [[META144:![0-9]+]], metadata !DIExpression()), !dbg [[DBG147:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 0, i32* [[I185]], align 4, !dbg [[DBG147]] // CHECK-DEBUG-NEXT: [[TMP0:%.*]] = getelementptr inbounds [[STRUCT_ANON_17]], %struct.anon.17* [[AGG_CAPTURED186]], i32 0, i32 0, !dbg [[DBG148:![0-9]+]] // CHECK-DEBUG-NEXT: store i32* [[I185]], i32** [[TMP0]], align 8, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP1:%.*]] = getelementptr inbounds [[STRUCT_ANON_18]], %struct.anon.18* [[AGG_CAPTURED187]], i32 0, i32 0, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP2:%.*]] = load i32, i32* [[I185]], align 4, !dbg [[DBG149:![0-9]+]] // CHECK-DEBUG-NEXT: store i32 [[TMP2]], i32* [[TMP1]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: call void @__captured_stmt.19(i32* [[DOTCOUNT_ADDR188]], %struct.anon.17* [[AGG_CAPTURED186]]), !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[DOTCOUNT189:%.*]] = load i32, i32* [[DOTCOUNT_ADDR188]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_PREHEADER190:%.*]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.preheader190: // CHECK-DEBUG-NEXT: store i32 0, i32* [[P_LOWERBOUND204]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP3:%.*]] = sub i32 [[DOTCOUNT189]], 1, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: store i32 [[TMP3]], i32* [[P_UPPERBOUND205]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: store i32 1, i32* [[P_STRIDE206]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM207:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB42:[0-9]+]]), !dbg [[DBG148]] // CHECK-DEBUG-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @[[GLOB42]], i32 [[OMP_GLOBAL_THREAD_NUM207]], i32 34, i32* [[P_LASTITER203]], i32* [[P_LOWERBOUND204]], i32* [[P_UPPERBOUND205]], i32* [[P_STRIDE206]], i32 1, i32 0), !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP4:%.*]] = load i32, i32* [[P_LOWERBOUND204]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP5:%.*]] = load i32, i32* [[P_UPPERBOUND205]], align 4, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP6:%.*]] = sub i32 [[TMP5]], [[TMP4]], !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP7:%.*]] = add i32 [[TMP6]], 1, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_HEADER191:%.*]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.header191: // CHECK-DEBUG-NEXT: [[OMP_LOOP_IV197:%.*]] = phi i32 [ 0, [[OMP_LOOP_PREHEADER190]] ], [ [[OMP_LOOP_NEXT199:%.*]], [[OMP_LOOP_INC194:%.*]] ], !dbg [[DBG148]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_COND192:%.*]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.cond192: // CHECK-DEBUG-NEXT: [[OMP_LOOP_CMP198:%.*]] = icmp ult i32 [[OMP_LOOP_IV197]], [[TMP7]], !dbg [[DBG148]] // CHECK-DEBUG-NEXT: br i1 [[OMP_LOOP_CMP198]], label [[OMP_LOOP_BODY193:%.*]], label [[OMP_LOOP_EXIT195:%.*]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.body193: // CHECK-DEBUG-NEXT: [[TMP8:%.*]] = add i32 [[OMP_LOOP_IV197]], [[TMP4]], !dbg [[DBG150:![0-9]+]] // CHECK-DEBUG-NEXT: call void @__captured_stmt.20(i32* [[I185]], i32 [[TMP8]], %struct.anon.18* [[AGG_CAPTURED187]]), !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[TMP9:%.*]] = load i32, i32* [[A_ADDR]], align 4, !dbg [[DBG151:![0-9]+]] // CHECK-DEBUG-NEXT: [[CONV200:%.*]] = sitofp i32 [[TMP9]] to double, !dbg [[DBG151]] // CHECK-DEBUG-NEXT: [[TMP10:%.*]] = load double, double* [[B_ADDR]], align 8, !dbg [[DBG150]] // CHECK-DEBUG-NEXT: [[ADD201:%.*]] = fadd double [[CONV200]], [[TMP10]], !dbg [[DBG152:![0-9]+]] // CHECK-DEBUG-NEXT: [[CONV202:%.*]] = fptrunc double [[ADD201]] to float, !dbg [[DBG151]] // CHECK-DEBUG-NEXT: [[TMP11:%.*]] = load float*, float** [[R_ADDR]], align 8, !dbg [[DBG153:![0-9]+]] // CHECK-DEBUG-NEXT: store float [[CONV202]], float* [[TMP11]], align 4, !dbg [[DBG154:![0-9]+]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_INC194]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.inc194: // CHECK-DEBUG-NEXT: [[OMP_LOOP_NEXT199]] = add nuw i32 [[OMP_LOOP_IV197]], 1, !dbg [[DBG148]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_HEADER191]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.exit195: // CHECK-DEBUG-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB42]], i32 [[OMP_GLOBAL_THREAD_NUM207]]), !dbg [[DBG148]] // CHECK-DEBUG-NEXT: [[OMP_GLOBAL_THREAD_NUM208:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB42]]), !dbg [[DBG150]] // CHECK-DEBUG-NEXT: call void @__kmpc_barrier(%struct.ident_t* @[[GLOB43:[0-9]+]], i32 [[OMP_GLOBAL_THREAD_NUM208]]), !dbg [[DBG150]] // CHECK-DEBUG-NEXT: br label [[OMP_LOOP_AFTER196:%.*]], !dbg [[DBG148]] // CHECK-DEBUG: omp_loop.after196: // CHECK-DEBUG-NEXT: ret void, !dbg [[DBG155:![0-9]+]] // void parallel_for_2(float *r, int a, double b) { #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; #pragma omp parallel { #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #pragma omp for for (int i = 0; i < 100; ++i) *r = a + b; } #endif
compiler_cgen.c
/* Generated by Nim Compiler v0.15.0 */ /* (c) 2016 Andreas Rumpf */ /* The generated code is subject to the original license. */ #define NIM_INTBITS 64 #include "nimbase.h" #include <string.h> typedef struct Tcgen527027 Tcgen527027; typedef struct TNimType TNimType; typedef struct TNimNode TNimNode; typedef struct Ropeobj177006 Ropeobj177006; typedef struct NimStringDesc NimStringDesc; typedef struct TGenericSeq TGenericSeq; typedef struct Cell46904 Cell46904; typedef struct Cellseq46920 Cellseq46920; typedef struct Gcheap49418 Gcheap49418; typedef struct Gcstack49416 Gcstack49416; typedef struct Memregion29086 Memregion29086; typedef struct Smallchunk29040 Smallchunk29040; typedef struct Llchunk29080 Llchunk29080; typedef struct Bigchunk29042 Bigchunk29042; typedef struct Intset29014 Intset29014; typedef struct Trunk29010 Trunk29010; typedef struct Avlnode29084 Avlnode29084; typedef struct Gcstat49414 Gcstat49414; typedef struct Cellset46916 Cellset46916; typedef struct Pagedesc46912 Pagedesc46912; typedef struct Ttypeseq290836 Ttypeseq290836; typedef struct Ttype290840 Ttype290840; typedef struct Intset266030 Intset266030; typedef struct Trunk266026 Trunk266026; typedef struct Trunkseq266028 Trunkseq266028; typedef struct Tpasscontext339002 Tpasscontext339002; typedef struct Tsym290834 Tsym290834; typedef struct Tidobj197004 Tidobj197004; typedef struct TNimObject TNimObject; typedef struct TY290929 TY290929; typedef struct Tstrtable290806 Tstrtable290806; typedef struct Tsymseq290804 Tsymseq290804; typedef struct Tident197010 Tident197010; typedef struct Tlineinfo189336 Tlineinfo189336; typedef struct Tnode290802 Tnode290802; typedef struct Tloc290816 Tloc290816; typedef struct Tlib290820 Tlib290820; typedef struct TY527153 TY527153; typedef struct TY201018 TY201018; typedef struct Tidtable290850 Tidtable290850; typedef struct Tidpairseq290848 Tidpairseq290848; typedef struct Tlinkedlist147013 Tlinkedlist147013; typedef struct Tlistentry147007 Tlistentry147007; typedef struct Tcproc527021 Tcproc527021; typedef struct Tnodetable290862 Tnodetable290862; typedef struct Tnodepairseq290860 Tnodepairseq290860; typedef struct Debuginfo201009 Debuginfo201009; typedef struct TY201021 TY201021; typedef struct TY201023 TY201023; typedef struct Tnodeseq290796 Tnodeseq290796; typedef struct TY189350 TY189350; typedef struct TY527095 TY527095; typedef struct Trodreader330021 Trodreader330021; typedef struct TY290960 TY290960; typedef struct TY201017 TY201017; typedef struct Enumdesc201007 Enumdesc201007; typedef struct Tinfocc271008 Tinfocc271008; typedef struct Tblock527019 Tblock527019; typedef struct Ttraversalclosure535019 Ttraversalclosure535019; typedef struct TY134602 TY134602; typedef struct Tbitset337004 Tbitset337004; typedef struct TY189612 TY189612; typedef struct Tfileinfo189334 Tfileinfo189334; typedef struct Tinfoos175035 Tinfoos175035; typedef struct Tinfocpu175476 Tinfocpu175476; typedef struct Tstrentry147009 Tstrentry147009; typedef struct TY124315 TY124315; typedef struct Basechunk29038 Basechunk29038; typedef struct Freecell29030 Freecell29030; typedef struct Tinstantiation290824 Tinstantiation290824; typedef struct Tidpair290846 Tidpair290846; typedef struct Tnodepair290858 Tnodepair290858; typedef struct Filenamemapping201005 Filenamemapping201005; typedef struct TY330033 TY330033; typedef struct Tindex330019 Tindex330019; typedef struct Tiitable297142 Tiitable297142; typedef struct Tiipairseq297140 Tiipairseq297140; typedef struct Table330054 Table330054; typedef struct Keyvaluepairseq330057 Keyvaluepairseq330057; typedef struct Memfile328202 Memfile328202; typedef struct TY290961 TY290961; typedef struct Tiipair297138 Tiipair297138; typedef struct Keyvaluepair330060 Keyvaluepair330060; typedef NU8 Tnimkind3403; typedef NU8 Tnimtypeflag3409Set; typedef N_NIMCALL_PTR(void, TY3489) (void* p0, NI op0); typedef N_NIMCALL_PTR(void*, TY3494) (void* p0); struct TNimType { NI size; Tnimkind3403 kind; Tnimtypeflag3409Set flags; TNimType* base; TNimNode* node; void* finalizer; TY3489 marker; TY3494 deepcopy; }; typedef NU8 Tnimnodekind3405; struct TNimNode { Tnimnodekind3405 kind; NI offset; TNimType* typ; NCSTRING name; NI len; TNimNode** sons; }; typedef N_NIMCALL_PTR(void, Globalmarkerproc55402) (void); struct TGenericSeq { NI len; NI reserved; }; struct NimStringDesc { TGenericSeq Sup; NIM_CHAR data[SEQ_DECL_SIZE]; }; struct Cell46904 { NI refcount; TNimType* typ; }; struct Cellseq46920 { NI len; NI cap; Cell46904** d; }; typedef Smallchunk29040* TY29101[512]; typedef Trunk29010* Trunkbuckets29012[256]; struct Intset29014 { Trunkbuckets29012 data; }; struct Memregion29086 { NI minlargeobj; NI maxlargeobj; TY29101 freesmallchunks; Llchunk29080* llmem; NI currmem; NI maxmem; NI freemem; NI lastsize; Bigchunk29042* freechunkslist; Intset29014 chunkstarts; Avlnode29084* root; Avlnode29084* deleted; Avlnode29084* last; Avlnode29084* freeavlnodes; NIM_BOOL locked; }; struct Gcstat49414 { NI stackscans; NI cyclecollections; NI maxthreshold; NI maxstacksize; NI maxstackcells; NI cycletablesize; NI64 maxpause; }; struct Cellset46916 { NI counter; NI max; Pagedesc46912* head; Pagedesc46912** data; }; struct Gcheap49418 { Gcstack49416* stack; void* stackbottom; NI cyclethreshold; Cellseq46920 zct; Cellseq46920 decstack; Cellseq46920 tempstack; NI recgclock; Memregion29086 region; Gcstat49414 stat; Cellset46916 marked; Cellseq46920 additionalroots; }; struct Intset266030 { NI counter; NI max; Trunk266026* head; Trunkseq266028* data; }; struct TNimObject { TNimType* m_type; }; struct Tidobj197004 { TNimObject Sup; NI id; }; typedef NU8 Tsymkind290435; struct Tstrtable290806 { NI counter; Tsymseq290804* data; }; typedef NU16 Tmagic290524; struct Tlineinfo189336 { NI16 line; NI16 col; NI32 fileindex; }; typedef NU32 Tsymflag290184Set; typedef NU32 Toption168009Set; typedef NU8 Tlockind290808; typedef NU8 Tstorageloc290812; typedef NU16 Tlocflag290810Set; struct Tloc290816 { Tlockind290808 k; Tstorageloc290812 s; Tlocflag290810Set flags; Ttype290840* t; Ropeobj177006* r; }; struct Tsym290834 { Tidobj197004 Sup; Tsymkind290435 kind; union{ struct {Ttypeseq290836* typeinstcache; } S1; struct {TY290929* procinstcache; Tsym290834* gcunsafetyreason; } S2; struct {TY290929* usedgenerics; Tstrtable290806 tab; } S3; struct {Tsym290834* guard; NI bitsize; } S4; } kindU; Tmagic290524 magic; Ttype290840* typ; Tident197010* name; Tlineinfo189336 info; Tsym290834* owner; Tsymflag290184Set flags; Tnode290802* ast; Toption168009Set options; NI position; NI offset; Tloc290816 loc; Tlib290820* annex; Tnode290802* constraint; }; struct TY201018 { NimStringDesc* Field0; NI Field1; }; struct Tpasscontext339002 { TNimObject Sup; NIM_BOOL fromcache; }; typedef Ropeobj177006* Tcfilesections527009[18]; typedef NU8 Codegenflag527025Set; struct Tidtable290850 { NI counter; Tidpairseq290848* data; }; struct Tlinkedlist147013 { Tlistentry147007* head; Tlistentry147007* tail; NI counter; }; struct Tnodetable290862 { NI counter; Tnodepairseq290860* data; }; typedef Ropeobj177006* TY527136[10]; struct Tcgen527027 { Tpasscontext339002 Sup; Tcfilesections527009 s; Codegenflag527025Set flags; Tsym290834* module; NimStringDesc* filename; NimStringDesc* cfilename; Ropeobj177006* tmpbase; Tidtable290850 typecache; Tidtable290850 forwtypecache; Intset266030 declaredthings; Intset266030 declaredprotos; Tlinkedlist147013 headerfiles; Intset266030 typeinfomarker; Tcproc527021* initproc; Tcproc527021* postinitproc; Tcproc527021* preinitproc; Ttypeseq290836* typestack; Tnodetable290862 datacache; Tsymseq290804* forwardedprocs; NI typenodes; NI nimtypes; Ropeobj177006* typenodesname; Ropeobj177006* nimtypesname; NI labels; TY527136 extensionloaders; Ropeobj177006* injectstmt; }; struct Debuginfo201009 { NI version; TY201021* files; TY201023* enums; NIM_BOOL conflicts; }; struct Tident197010 { Tidobj197004 Sup; NimStringDesc* s; Tident197010* next; NI h; }; struct Tcproc527021 { Tsym290834* prc; NIM_BOOL beforeretneeded; NIM_BOOL threadvaraccessed; Tlineinfo189336 lastlineinfo; Tnodeseq290796* nestedtrystmts; NI inexceptblock; TY189350* finallysafepoints; NI labels; TY527095* blocks; NI breakidx; Toption168009Set options; NI maxframelen; Tcgen527027* module; NI withinloop; NI splitdecls; NI gcframeid; Ropeobj177006* gcframetype; }; typedef NU8 Tsymflag290184; typedef NU8 Codegenflag527025; typedef NU8 Toption168009; typedef NU64 Tglobaloption168013Set; typedef NU8 Tglobaloption168013; typedef NU8 Tcommands168076; typedef NU16 Tnodeflag290427Set; typedef NU8 Tnodekind290020; struct Tnode290802 { Ttype290840* typ; Tlineinfo189336 info; Tnodeflag290427Set flags; Tnodekind290020 kind; union{ struct {NI64 intval; } S1; struct {NF floatval; } S2; struct {NimStringDesc* strval; } S3; struct {Tsym290834* sym; } S4; struct {Tident197010* ident; } S5; struct {Tnodeseq290796* sons; } S6; } kindU; NimStringDesc* comment; }; typedef Ropeobj177006* TY531289[1]; typedef NU8 Tlocflag290810; struct Tlistentry147007 { TNimObject Sup; Tlistentry147007* prev; Tlistentry147007* next; }; typedef NU8 Tlibkind290818; struct Tlib290820 { Tlistentry147007 Sup; Tlibkind290818 kind; NIM_BOOL generated; NIM_BOOL isoverriden; Ropeobj177006* name; Tnode290802* path; }; typedef NU8 Tcfilesection527005; typedef NU8 Ttypekind290244; typedef NU8 Tcallingconvention290002; typedef NU32 Ttypeflag290431Set; struct Ttype290840 { Tidobj197004 Sup; Ttypekind290244 kind; Tcallingconvention290002 callconv; Ttypeflag290431Set flags; Ttypeseq290836* sons; Tnode290802* n; Tsym290834* owner; Tsym290834* sym; Tsym290834* destructor; Tsym290834* deepcopy; Tsym290834* assignment; TY290960* methods; NI64 size; NI16 align; NI16 locklevel; Tloc290816 loc; }; typedef Ropeobj177006* TY530811[2]; typedef NU8 Tctypekind527007; typedef NU64 Ttypekind290244Set; typedef NU8 Ttypeflag290431; typedef NimStringDesc* TY531943[14]; typedef NU8 Tprefereddesc318011; typedef Ropeobj177006* TY177507[1]; struct Enumdesc201007 { NI size; NU32 owner; NI id; NimStringDesc* name; TY201017* values; }; typedef Ropeobj177006* TY533235[4]; typedef NimStringDesc* TY290016[10]; typedef Ropeobj177006* TY533238[3]; struct Ropeobj177006 { TNimObject Sup; Ropeobj177006* left; Ropeobj177006* right; NI length; NimStringDesc* data; }; typedef NU8 Tinfoccprop271004Set; struct Tinfocc271008 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; NimStringDesc* Field3; NimStringDesc* Field4; NimStringDesc* Field5; NimStringDesc* Field6; NimStringDesc* Field7; NimStringDesc* Field8; NimStringDesc* Field9; NimStringDesc* Field10; NimStringDesc* Field11; NimStringDesc* Field12; NimStringDesc* Field13; NimStringDesc* Field14; NimStringDesc* Field15; NimStringDesc* Field16; NimStringDesc* Field17; NimStringDesc* Field18; NimStringDesc* Field19; Tinfoccprop271004Set Field20; }; typedef Tinfocc271008 TY271427[13]; typedef NU8 Tsystemcc271002; typedef NU8 Tnodeflag290427; typedef NU8 Tcprocsection527011; typedef Ropeobj177006* Tcprocsections527013[3]; struct Tblock527019 { NI id; Ropeobj177006* label; Tcprocsections527013 sections; NIM_BOOL isloop; NI16 nestedtrystmts; NI16 nestedexceptstmts; NI16 framelen; }; typedef NU8 Tgcmode168080; typedef NU8 Ttypeinforeason535016; struct Ttraversalclosure535019 { Tcproc527021* p; NimStringDesc* visitorfrmt; }; typedef NU8 Ttypefieldresult318145; typedef NU8 Tinfoccprop271004; typedef Ropeobj177006* TY534847[6]; typedef Ropeobj177006* TY534401[7]; typedef Ropeobj177006* TY534475[5]; typedef NU16 Tmsgkind189002; typedef NU8 Tassignmentflag536302Set; typedef NU8 Tassignmentflag536302; typedef NimStringDesc* TY550655[19]; typedef NimStringDesc* TY549642[3]; typedef NimStringDesc* TY554765[4]; typedef NimStringDesc* TY549828[42]; typedef NimStringDesc* TY549281[7]; typedef NU8 Trenderflag309004Set; typedef NimStringDesc* TY555052[2]; typedef NU8 Tclosuretypekind533681; typedef NimStringDesc* TY554428[6]; typedef NU8 Tanalysisresult471003; typedef NU8 char136Set[32]; typedef NU8 Tdistinctcompare322427; typedef NU8 Ttypecmpflag322429Set; typedef NU16 Tspecialword273003; typedef NU8 Tsystemos175004; struct Tfileinfo189334 { NimStringDesc* fullpath; NimStringDesc* projpath; NimStringDesc* shortname; Ropeobj177006* quotedname; Ropeobj177006* quotedfullname; TY189350* lines; NimStringDesc* dirtyfile; }; typedef NU8 Tinfoosprop175031Set; struct Tinfoos175035 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; NimStringDesc* Field3; NimStringDesc* Field4; NimStringDesc* Field5; NimStringDesc* Field6; NimStringDesc* Field7; NimStringDesc* Field8; NimStringDesc* Field9; NimStringDesc* Field10; NimStringDesc* Field11; Tinfoosprop175031Set Field12; }; typedef Tinfoos175035 TY175082[24]; typedef NU8 Tendian175474; struct Tinfocpu175476 { NimStringDesc* Field0; NI Field1; Tendian175474 Field2; NI Field3; NI Field4; }; typedef Tinfocpu175476 TY175510[19]; typedef NU8 Tsystemcpu175452; struct Tstrentry147009 { Tlistentry147007 Sup; NimStringDesc* data; }; struct TY124315 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; }; struct Gcstack49416 { Gcstack49416* prev; Gcstack49416* next; void* starts; void* pos; NI maxstacksize; }; struct Basechunk29038 { NI prevsize; NI size; NIM_BOOL used; }; struct Smallchunk29040 { Basechunk29038 Sup; Smallchunk29040* next; Smallchunk29040* prev; Freecell29030* freelist; NI free; NI acc; NF data; }; struct Llchunk29080 { NI size; NI acc; Llchunk29080* next; }; struct Bigchunk29042 { Basechunk29038 Sup; Bigchunk29042* next; Bigchunk29042* prev; NI align; NF data; }; typedef NI TY29019[8]; struct Trunk29010 { Trunk29010* next; NI key; TY29019 bits; }; typedef Avlnode29084* TY29091[2]; struct Avlnode29084 { TY29091 link; NI key; NI upperbound; NI level; }; struct Pagedesc46912 { Pagedesc46912* next; NI key; TY29019 bits; }; struct Trunk266026 { Trunk266026* next; NI key; TY29019 bits; }; struct Tidpair290846 { Tidobj197004* key; TNimObject* val; }; struct Tnodepair290858 { NI h; Tnode290802* key; NI val; }; struct Filenamemapping201005 { NimStringDesc* package; NimStringDesc* file; NU32 mangled; }; typedef NU8 Treasonforrecompile330002; struct Tiitable297142 { NI counter; Tiipairseq297140* data; }; struct Tindex330019 { NI lastidxkey; NI lastidxval; Tiitable297142 tab; NimStringDesc* r; NI offset; }; struct Table330054 { Keyvaluepairseq330057* data; NI counter; }; struct Memfile328202 { void* mem; NI size; NI fhandle; NI maphandle; NIM_BOOL wasopened; }; struct Trodreader330021 { TNimObject Sup; NI pos; NCSTRING s; Toption168009Set options; Treasonforrecompile330002 reason; TY330033* moddeps; TY330033* files; NI dataidx; NI convertersidx; NI initidx; NI interfidx; NI compilerprocsidx; NI methodsidx; NimStringDesc* filename; Tindex330019 index; Tindex330019 imports; NI readerindex; NI line; NI moduleid; Table330054 syms; Memfile328202 memfile; Tsymseq290804* methods; NimStringDesc* origfile; NIM_BOOL inviewmode; }; struct TY290961 { NI Field0; Tsym290834* Field1; }; struct Freecell29030 { Freecell29030* next; NI zerofield; }; struct Tinstantiation290824 { Tsym290834* sym; Ttypeseq290836* concretetypes; NI compilesid; }; struct Tiipair297138 { NI key; NI val; }; struct Keyvaluepair330060 { NI Field0; NI Field1; Tsym290834* Field2; }; struct Ttypeseq290836 { TGenericSeq Sup; Ttype290840* data[SEQ_DECL_SIZE]; }; struct TY527153 { TGenericSeq Sup; Tcgen527027* data[SEQ_DECL_SIZE]; }; struct Tsymseq290804 { TGenericSeq Sup; Tsym290834* data[SEQ_DECL_SIZE]; }; struct TY201017 { TGenericSeq Sup; TY201018 data[SEQ_DECL_SIZE]; }; struct TY134602 { TGenericSeq Sup; NimStringDesc* data[SEQ_DECL_SIZE]; }; struct Tbitset337004 { TGenericSeq Sup; NI8 data[SEQ_DECL_SIZE]; }; struct TY527095 { TGenericSeq Sup; Tblock527019 data[SEQ_DECL_SIZE]; }; struct TY189350 { TGenericSeq Sup; Ropeobj177006* data[SEQ_DECL_SIZE]; }; struct Tnodeseq290796 { TGenericSeq Sup; Tnode290802* data[SEQ_DECL_SIZE]; }; struct TY189612 { TGenericSeq Sup; Tfileinfo189334 data[SEQ_DECL_SIZE]; }; struct Trunkseq266028 { TGenericSeq Sup; Trunk266026* data[SEQ_DECL_SIZE]; }; struct TY290929 { TGenericSeq Sup; Tinstantiation290824* data[SEQ_DECL_SIZE]; }; struct Tidpairseq290848 { TGenericSeq Sup; Tidpair290846 data[SEQ_DECL_SIZE]; }; struct Tnodepairseq290860 { TGenericSeq Sup; Tnodepair290858 data[SEQ_DECL_SIZE]; }; struct TY201021 { TGenericSeq Sup; Filenamemapping201005 data[SEQ_DECL_SIZE]; }; struct TY201023 { TGenericSeq Sup; Enumdesc201007 data[SEQ_DECL_SIZE]; }; struct TY290960 { TGenericSeq Sup; TY290961 data[SEQ_DECL_SIZE]; }; struct TY330033 { TGenericSeq Sup; NI32 data[SEQ_DECL_SIZE]; }; struct Tiipairseq297140 { TGenericSeq Sup; Tiipair297138 data[SEQ_DECL_SIZE]; }; struct Keyvaluepairseq330057 { TGenericSeq Sup; Keyvaluepair330060 data[SEQ_DECL_SIZE]; }; N_NIMCALL(void, nimGCvisit)(void* d0, NI op0); N_NIMCALL(void, T839829468_2)(void); N_NIMCALL(void, nimRegisterGlobalMarker)(Globalmarkerproc55402 markerproc0); N_NIMCALL(void, T839829468_3)(void); N_NIMCALL(Ropeobj177006*, rope_177277_2381377266)(NimStringDesc* s0); static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0); static N_INLINE(Cell46904*, usrtocell_51040_1689653243)(void* usr0); static N_INLINE(void, rtladdzct_52201_1689653243)(Cell46904* c0); N_NOINLINE(void, addzct_51017_1689653243)(Cellseq46920* s0, Cell46904* c0); N_NIMCALL(void, T839829468_5)(void); N_NIMCALL(void, T839829468_6)(void); static N_INLINE(void, nimGCunrefNoCycle)(void* p0); N_NIMCALL(void*, newSeqRC1)(TNimType* typ0, NI len0); N_NIMCALL(void, T839829468_7)(void); N_NIMCALL(void, initintset_266885_2627731572)(Intset266030* Result); N_NOINLINE(void, chckNil)(void* p0); N_NIMCALL(void, genericReset)(void* dest0, TNimType* mt0); N_NIMCALL(void, T839829468_8)(void); N_NIMCALL(Tcgen527027*, newmodule_561044_839829468)(Tsym290834* module0); N_NIMCALL(Tcgen527027*, getcgenmodule_530226_839829468)(Tsym290834* s0); N_NIMCALL(void, internalerror_194113_155036129)(NimStringDesc* errmsg0); N_NIMCALL(NimStringDesc*, HEX24_194185_1689653243)(TY201018 x0); N_NIMCALL(Tcgen527027*, rawnewmodule_561038_839829468)(Tsym290834* module0); N_NIMCALL(Tcgen527027*, rawnewmodule_560663_839829468)(Tsym290834* module0, NimStringDesc* filename0); N_NIMCALL(void*, newObj)(TNimType* typ0, NI size0); static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0); static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0); N_NIMCALL(NimStringDesc*, HEX24_8401_1689653243)(NU64 x0); N_NIMCALL(NU32, hashowner_530977_839829468)(Tsym290834* s0); N_NIMCALL(NU32, register_201121_1926258066)(Debuginfo201009* self0, NimStringDesc* package0, NimStringDesc* file0); N_NIMCALL(NimStringDesc*, rawNewString)(NI space0); N_NIMCALL(void, initlinkedlist_147031_3771138726)(Tlinkedlist147013* list0); N_NIMCALL(NimStringDesc*, copyStringRC1)(NimStringDesc* src0); N_NIMCALL(void, initidtable_294019_850551059)(Tidtable290850* x0); N_NIMCALL(Tcproc527021*, newproc_527206_3723162438)(Tsym290834* prc0, Tcgen527027* module0); static N_INLINE(void, asgnRef)(void** dest0, void* src0); static N_INLINE(void, incref_53019_1689653243)(Cell46904* c0); static N_INLINE(void, decref_52601_1689653243)(Cell46904* c0); N_NIMCALL(Toption168009Set, initprocoptions_560635_839829468)(Tcgen527027* m0); N_NIMCALL(Tcproc527021*, newpreinitproc_560625_839829468)(Tcgen527027* m0); N_NIMCALL(Tcproc527021*, newpostinitproc_560630_839829468)(Tcgen527027* m0); N_NIMCALL(void, initnodetable_294085_850551059)(Tnodetable290862* x0); N_NIMCALL(Ropeobj177006*, gettempname_531598_839829468)(Tcgen527027* m0); N_NIMCALL(Ropeobj177006*, HEX26_177418_2381377266)(Ropeobj177006* a0, Ropeobj177006* b0); N_NIMCALL(Ropeobj177006*, rope_177401_2381377266)(NI64 i0); N_NIMCALL(NimStringDesc*, tofullpath_190261_155036129)(NI32 fileidx0); N_NIMCALL(TGenericSeq*, setLengthSeq)(TGenericSeq* seq0, NI elemsize0, NI newlen0); N_NIMCALL(NimStringDesc*, tofilename_190257_155036129)(NI32 fileidx0); N_NIMCALL(NimStringDesc*, noschangeFileExt)(NimStringDesc* filename0, NimStringDesc* ext0); N_NIMCALL(NimStringDesc*, completecfilepath_271854_2528170400)(NimStringDesc* cfile0, NIM_BOOL createsubdir0); N_NIMCALL(void, readmergeinfo_528613_2760143328)(NimStringDesc* cfilename0, Tcgen527027* m0); N_NIMCALL(NimStringDesc*, getcfile_561201_839829468)(Tcgen527027* m0); N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src0); N_NIMCALL(NimStringDesc*, withpackagename_169065_2607990831)(NimStringDesc* path0); static N_INLINE(NIM_BOOL, skipcodegen_339085_2355241294)(Tnode290802* n0); N_NIMCALL(void, genstmts_537244_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(void, expr_537248_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, fillprocloc_537201_839829468)(Tsym290834* sym0); N_NIMCALL(void, fillloc_530282_839829468)(Tloc290816* a0, Tlockind290808 k0, Ttype290840* typ0, Ropeobj177006* r0, Tstorageloc290812 s0); N_NIMCALL(void, unsureAsgnRef)(void** dest0, void* src0); N_NIMCALL(Ropeobj177006*, manglename_531205_839829468)(Tsym290834* s0); N_NIMCALL(NIM_BOOL, iskeyword_530960_839829468)(Tident197010* w0); N_NIMCALL(NimStringDesc*, mangle_526847_2036603609)(NimStringDesc* name0); N_NIMCALL(void, add_177487_2381377266)(Ropeobj177006** a0, NimStringDesc* b0); N_NIMCALL(void, add_177482_2381377266)(Ropeobj177006** a0, Ropeobj177006* b0); N_NIMCALL(Ropeobj177006*, HEX25_177905_2381377266)(NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(void, genprocprototype_537254_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(void, useheader_530369_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(NIM_BOOL, includestr_147249_3771138726)(Tlinkedlist147013* list0, NimStringDesc* data0); N_NIMCALL(NimStringDesc*, getstr_295230_850551059)(Tnode290802* a0); N_NIMCALL(Tsym290834*, getmodule_297123_2984716966)(Tsym290834* s0); N_NIMCALL(NIM_BOOL, containsorincl_266862_2627731572)(Intset266030* s0, NI key0); N_NIMCALL(Ropeobj177006*, ropecg_530407_839829468)(Tcgen527027* m0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(NimStringDesc*, nimIntToStr)(NI x0); static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0); N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI start_78810_1689653243, NI last0); N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI first0, NI last0); N_NIMCALL(Ropeobj177006*, cgsym_530403_839829468)(Tcgen527027* m0, NimStringDesc* name0); N_NIMCALL(Tsym290834*, getcompilerproc_336748_3937434831)(NimStringDesc* name0); N_NIMCALL(void, genproc_530951_839829468)(Tcgen527027* m0, Tsym290834* prc0); N_NIMCALL(NIM_BOOL, isactivated_559431_839829468)(Tsym290834* prc0); N_NIMCALL(void, addforwardedproc_530203_839829468)(Tcgen527027* m0, Tsym290834* prc0); N_NIMCALL(TGenericSeq*, incrSeqV2)(TGenericSeq* seq0, NI elemsize0); N_NIMCALL(void, genprocnoforward_558906_839829468)(Tcgen527027* m0, Tsym290834* prc0); N_NIMCALL(void, genprocaux_558284_839829468)(Tcgen527027* m0, Tsym290834* prc0); N_NIMCALL(Ropeobj177006*, genprocheader_533867_839829468)(Tcgen527027* m0, Tsym290834* prc0); N_NIMCALL(void, genclinedir_530813_839829468)(Ropeobj177006** r0, Tlineinfo189336 info0); N_NIMCALL(void, genclinedir_530725_839829468)(Ropeobj177006** r0, NimStringDesc* filename0, NI line0); N_NIMCALL(void, addf_178205_2381377266)(Ropeobj177006** c0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(NimStringDesc*, makesinglelinecstring_526835_2036603609)(NimStringDesc* s0); N_NIMCALL(NI, safelinenm_530721_839829468)(Tlineinfo189336 info0); static N_INLINE(NI, tolinenumber_190415_155036129)(Tlineinfo189336 info0); N_NIMCALL(void, genprocparams_532115_839829468)(Tcgen527027* m0, Ttype290840* t0, Ropeobj177006** rettype0, Ropeobj177006** params0, Intset266030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0); N_NIMCALL(NIM_BOOL, isinvalidreturntype_531550_839829468)(Ttype290840* rettype0); N_NIMCALL(Tctypekind527007, maptype_531394_839829468)(Ttype290840* typ0); N_NIMCALL(Tctypekind527007, mapsettype_531389_839829468)(Ttype290840* typ0); N_NIMCALL(NI64, getsize_318135_3876443242)(Ttype290840* typ0); N_NIMCALL(Ttype290840*, lastson_293377_850551059)(Ttype290840* n0); N_NIMCALL(NI64, firstord_318001_3876443242)(Ttype290840* t0); N_NIMCALL(Ttype290840*, skiptypes_294099_850551059)(Ttype290840* t0, Ttypekind290244Set kinds0); N_NIMCALL(NIM_BOOL, isimportedcpptype_531478_839829468)(Ttype290840* t0); N_NIMCALL(NIM_BOOL, needscomplexassignment_531511_839829468)(Ttype290840* typ0); N_NIMCALL(NIM_BOOL, containsgarbagecollectedref_318117_3876443242)(Ttype290840* typ0); static N_INLINE(NIM_BOOL, isobjlackingtypefield_531515_839829468)(Ttype290840* typ0); N_NIMCALL(NIM_BOOL, ispureobject_318138_3876443242)(Ttype290840* typ0); N_NIMCALL(Ropeobj177006*, gettypedescaux_531505_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0); N_NIMCALL(Ttype290840*, getuniquetype_526640_2036603609)(Ttype290840* key0); N_NIMCALL(Ropeobj177006*, gettypepre_531972_839829468)(Tcgen527027* m0, Ttype290840* typ0); N_NIMCALL(Ropeobj177006*, getsimpletypedesc_531936_839829468)(Tcgen527027* m0, Ttype290840* typ0); N_NIMCALL(Ropeobj177006*, typenameorliteral_531898_839829468)(Ttype290840* t0, NimStringDesc* literal0); N_NIMCALL(Ropeobj177006*, gettypename_531313_839829468)(Ttype290840* typ0); N_NIMCALL(Ropeobj177006*, typename_531292_839829468)(Ttype290840* typ0); N_NIMCALL(NimStringDesc*, reprEnum)(NI e0, TNimType* typ0); N_NIMCALL(Ropeobj177006*, cachegettype_531593_839829468)(Tidtable290850 tab0, Ttype290840* key0); N_NIMCALL(TNimObject*, idtableget_297086_2984716966)(Tidtable290850 t0, Tidobj197004* key0); N_NIMCALL(NimStringDesc*, typetostring_318017_3876443242)(Ttype290840* typ0, Tprefereddesc318011 prefer0); N_NIMCALL(Ttype290840*, elemtype_318394_3876443242)(Ttype290840* t0); N_NIMCALL(Ropeobj177006*, HEX26_177447_2381377266)(Ropeobj177006* a0, NimStringDesc* b0); N_NIMCALL(Ropeobj177006*, gettypeforward_532039_839829468)(Tcgen527027* m0, Ttype290840* typ0); N_NIMCALL(NIM_BOOL, isimportedtype_531451_839829468)(Ttype290840* t0); N_NIMCALL(NimStringDesc*, getforwardstructformat_532015_839829468)(Tcgen527027* m0); N_NIMCALL(Ropeobj177006*, structorunion_532001_839829468)(Ttype290840* t0); N_NIMCALL(void, idtableput_297094_2984716966)(Tidtable290850* t0, Tidobj197004* key0, TNimObject* val0); N_NIMCALL(void, pushtype_531958_839829468)(Tcgen527027* m0, Ttype290840* typ0); N_NIMCALL(Ropeobj177006*, gettypedescweak_532079_839829468)(Tcgen527027* m0, Ttype290840* t0, Intset266030* check0); N_NIMCALL(void, internalerror_194100_155036129)(Tlineinfo189336 info0, NimStringDesc* errmsg0); N_NIMCALL(NIM_BOOL, hasenum_201230_1926258066)(Debuginfo201009* self0, NimStringDesc* ename0, NI id0, NU32 owner0); N_NIMCALL(void*, newSeq)(TNimType* typ0, NI len0); static N_INLINE(NI, len_291081_850551059)(Tnode290802* n0); N_NIMCALL(void, registerenum_201419_1926258066)(Debuginfo201009* self0, Enumdesc201007* ed0); N_NIMCALL(void, genericSeqAssign)(void* dest0, void* src_86004_1689653243, TNimType* mt0); N_NIMCALL(void, appcg_530632_839829468)(Tcgen527027* m0, Ropeobj177006** c0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(NI64, lengthord_318007_3876443242)(Ttype290840* t0); N_NIMCALL(NIM_BOOL, scancppgenericslot_532827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0); N_NIMCALL(Ttype290840*, resolvestarsincpptype_532891_839829468)(Ttype290840* typ0, NI idx0, NI stars0); N_NIMCALL(NI, len_293339_850551059)(Ttype290840* n0); N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI start0); N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI first0); N_NIMCALL(Ropeobj177006*, getrecorddesc_532643_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0); N_NIMCALL(Ropeobj177006*, getrecordfields_532636_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0); N_NIMCALL(Ropeobj177006*, genrecordfieldsaux_532421_839829468)(Tcgen527027* m0, Tnode290802* n0, Ropeobj177006* accessexpr0, Ttype290840* rectype0, Intset266030* check0); N_NIMCALL(NI, sonslen_293351_850551059)(Tnode290802* n0); N_NIMCALL(Tnode290802*, lastson_293364_850551059)(Tnode290802* n0); N_NIMCALL(Ropeobj177006*, HEX26_177452_2381377266)(NimStringDesc* a0, Ropeobj177006* b0); N_NIMCALL(Ropeobj177006*, manglerecfieldname_532361_839829468)(Tsym290834* field0, Ttype290840* rectype0); N_NIMCALL(NimStringDesc*, manglefield_530973_839829468)(Tident197010* name0); N_NIMCALL(NIM_CHAR, nsuToUpperAsciiChar)(NIM_CHAR c0); N_NIMCALL(Ropeobj177006*, gettupledesc_532777_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0); N_NIMCALL(NI, sonslen_293327_850551059)(Ttype290840* n0); N_NIMCALL(void, excl_266841_2627731572)(Intset266030* s0, NI key0); static N_INLINE(NIM_BOOL, iscompiletimeonly_326706_3876443242)(Ttype290840* t0); N_NIMCALL(Tstorageloc290812, paramstorageloc_532098_839829468)(Tsym290834* param0); N_NIMCALL(NIM_BOOL, ccgintroducedptr_531611_839829468)(Tsym290834* s0); N_NIMCALL(Tctypekind527007, mapreturntype_531447_839829468)(Ttype290840* typ0); N_NIMCALL(Tnode290802*, easyresultasgn_558191_839829468)(Tnode290802* n0); static N_INLINE(Tnode290802*, HEX5BHEX5D_291238_850551059)(Tnode290802* n0, NI i0); N_NIMCALL(Tnode290802*, getbody_333226_1724185294)(Tsym290834* s0); N_NIMCALL(Ropeobj177006*, localvardecl_536532_839829468)(Tcproc527021* p0, Tsym290834* s0); N_NIMCALL(Ropeobj177006*, gettypedesc_533673_839829468)(Tcgen527027* m0, Ttype290840* typ0); N_NIMCALL(void, initlocexprsingleuse_537289_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0); N_NIMCALL(void, initloc_530273_839829468)(Tloc290816* result0, Tlockind290808 k0, Ttype290840* typ0, Tstorageloc290812 s0); N_NIMCALL(void, linefmt_530714_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); static N_INLINE(Ropeobj177006**, s_527179_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0); N_NIMCALL(Ropeobj177006*, indentline_530656_839829468)(Tcproc527021* p0, Ropeobj177006* r0); N_NIMCALL(void, prepend_177893_2381377266)(Ropeobj177006** a0, Ropeobj177006* b0); N_NIMCALL(Ropeobj177006*, rdloc_536188_839829468)(Tloc290816* a0); N_NIMCALL(void, assignlocalvar_536614_839829468)(Tcproc527021* p0, Tsym290834* s0); N_NIMCALL(void, line_530690_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, Ropeobj177006* r0); N_NIMCALL(void, localdebuginfo_536449_839829468)(Tcproc527021* p0, Tsym290834* s0); N_NIMCALL(void, linef_530700_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(Ropeobj177006*, makecstring_189638_155036129)(NimStringDesc* s0); N_NIMCALL(NimStringDesc*, nsuNormalize)(NimStringDesc* s0); N_NIMCALL(Ropeobj177006*, gentypeinfo_533941_839829468)(Tcgen527027* m0, Ttype290840* t_533944_839829468); N_NIMCALL(Tcgen527027*, bmod_527201_3723162438)(Tsym290834* module0); N_NIMCALL(void, gentypeinfoauxbase_533960_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0, Ropeobj177006* base0); N_NIMCALL(NIM_BOOL, canformacycle_318123_3876443242)(Ttype290840* typ0); N_NIMCALL(void, gentupleinfo_534551_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0); N_NIMCALL(Ropeobj177006*, getnimnode_533945_839829468)(Tcgen527027* m0); N_NIMCALL(Ttype290840*, fakeclosuretype_535010_839829468)(Tsym290834* owner0); N_NIMCALL(Ttype290840*, newtype_293107_850551059)(Ttypekind290244 kind0, Tsym290834* owner0); N_NIMCALL(void, rawaddson_294394_850551059)(Ttype290840* father0, Ttype290840* son0); N_NIMCALL(void, gentypeinfoaux_534027_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0); N_NIMCALL(Ropeobj177006*, gentraverseproc_535632_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttypeinforeason535016 reason0); N_NIMCALL(void, gentraverseprocseq_535399_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ0); N_NIMCALL(void, gettemp_535032_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816* result0, NIM_BOOL needsinit0); N_NIMCALL(void, constructloc_536388_839829468)(Tcproc527021* p0, Tloc290816* loc0, NIM_BOOL istemp0); static N_INLINE(NIM_BOOL, iscomplexvaluetype_536317_839829468)(Ttype290840* t0); N_NIMCALL(void, usestringh_530345_839829468)(Tcgen527027* m0); N_NIMCALL(Ropeobj177006*, addrloc_536204_839829468)(Tloc290816* a0); N_NIMCALL(void, genobjectinit_536242_839829468)(Tcproc527021* p0, Tcprocsection527011 section0, Ttype290840* t0, Tloc290816* a0, NIM_BOOL takeaddr0); N_NIMCALL(Ttypefieldresult318145, analyseobjectwithtypefield_318149_3876443242)(Ttype290840* t0); N_NIMCALL(Ttype290840*, getsystype_336150_3937434831)(Ttypekind290244 kind0); N_NIMCALL(void, gentraverseproc_535022_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ_535027_839829468); static N_INLINE(Ropeobj177006*, parentobj_535257_839829468)(Ropeobj177006* accessor0, Tcgen527027* m0); N_NIMCALL(void, gentraverseproc_535039_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Tnode290802* n0); N_NIMCALL(void, gencaserange_535028_839829468)(Tcproc527021* p0, Tnode290802* branch0); N_NIMCALL(Ropeobj177006*, genliteral_537273_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Ropeobj177006*, genliteral_547476_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* ty0); N_NIMCALL(Ropeobj177006*, intliteral_537270_839829468)(NI64 i0); N_NIMCALL(Ropeobj177006*, int64literal_547430_839829468)(NI64 i0); N_NIMCALL(Ropeobj177006*, uint64literal_547442_839829468)(NU64 i0); N_NIMCALL(NI, nodetabletestorset_340682_1142335848)(Tnodetable290862* t0, Tnode290802* key0, NI val0); N_NIMCALL(Ropeobj177006*, getstrlit_547468_839829468)(Tcgen527027* m0, NimStringDesc* s0); N_NIMCALL(NimStringDesc*, tostrmaxprecision_296007_3471544153)(NF f0); N_NIMCALL(Tnode290802*, copynode_294528_850551059)(Tnode290802* src0); N_NIMCALL(void, linecg_530707_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(void, genarrayinfo_535005_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0); N_NIMCALL(void, gensetinfo_534867_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0); N_NIMCALL(void, genenuminfo_534599_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0); N_NIMCALL(void, genobjectinfo_534508_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0); N_NIMCALL(void, genobjectfields_534104_839829468)(Tcgen527027* m0, Ttype290840* typ0, Tnode290802* n0, Ropeobj177006* expr0); N_NIMCALL(Ropeobj177006*, discriminatortablename_534057_839829468)(Tcgen527027* m0, Ttype290840* objtype_534060_839829468, Tsym290834* d0); N_NIMCALL(Tsym290834*, lookupinrecord_297119_2984716966)(Tnode290802* n0, Tident197010* field0); N_NIMCALL(NI64, getordvalue_318129_3876443242)(Tnode290802* n0); N_NIMCALL(void, gendeepcopyproc_536066_839829468)(Tcgen527027* m0, Tsym290834* s0, Ropeobj177006* result0); N_NIMCALL(void, initlocalvar_536398_839829468)(Tcproc527021* p0, Tsym290834* v0, NIM_BOOL immediateasgn0); N_NIMCALL(void, fillresult_531865_839829468)(Tsym290834* param0); N_NIMCALL(void, assignparam_536994_839829468)(Tcproc527021* p0, Tsym290834* s0); N_NIMCALL(void, closuresetup_558158_839829468)(Tcproc527021* p0, Tsym290834* prc0); N_NIMCALL(Ropeobj177006*, initgcframe_536435_839829468)(Tcproc527021* p0); N_NIMCALL(Ropeobj177006*, initframe_558140_839829468)(Tcproc527021* p0, Ropeobj177006* procname0, Ropeobj177006* filename0); N_NIMCALL(Ropeobj177006*, quotedfilename_194818_155036129)(Tlineinfo189336 i0); N_NIMCALL(void, appcg_530648_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(Ropeobj177006*, deinitgcframe_536441_839829468)(Tcproc527021* p0); N_NIMCALL(Ropeobj177006*, deinitframe_558150_839829468)(Tcproc527021* p0); N_NIMCALL(Tcgen527027*, findpendingmodule_530241_839829468)(Tcgen527027* m0, Tsym290834* s0); N_NIMCALL(void, symindynamiclib_557929_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(NIM_BOOL, isgetprocaddr_557443_839829468)(Tlib290820* lib0); N_NIMCALL(void, loaddynamiclib_557481_839829468)(Tcgen527027* m0, Tlib290820* lib0); N_NIMCALL(void, libcandidates_169605_2607990831)(NimStringDesc* s0, TY134602** dest0); N_NIMCALL(void, rawmessage_192612_155036129)(Tmsgkind189002 msg0, NimStringDesc* arg0); N_NIMCALL(void, initlocexpr_537283_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0); N_NIMCALL(Ropeobj177006*, mangledynlibproc_536816_839829468)(Tsym290834* sym0); N_NIMCALL(NimStringDesc*, HEX24_177856_2381377266)(Ropeobj177006* r0); N_NIMCALL(void, symindynamiclibpartial_558071_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(void, genvarprototype_537236_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(void, genvarprototypeaux_542254_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(void, declarethreadvar_536676_839829468)(Tcgen527027* m0, Tsym290834* s0, NIM_BOOL isextern0); static N_INLINE(NIM_BOOL, emulatedthreadvars_530949_839829468)(void); static N_INLINE(NIM_BOOL, crossescppboundary_558754_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(void, putlocintodest_537258_839829468)(Tcproc527021* p0, Tloc290816* d0, Tloc290816* s0); N_NIMCALL(void, genassignment_537264_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0); N_NIMCALL(void, genrefassign_536311_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0); static N_INLINE(NIM_BOOL, usesnativegc_168177_2607990831)(void); N_NIMCALL(void, optasgnloc_547789_839829468)(Tloc290816* a0, Ttype290840* t0, Ropeobj177006* field0, Tloc290816* Result); N_NIMCALL(void, genoptasgntuple_548001_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0); N_NIMCALL(void, gengenericasgn_548167_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0); N_NIMCALL(NI, asgncomplexity_547751_839829468)(Tnode290802* n0); N_NIMCALL(void, genoptasgnobject_548084_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0, Tnode290802* t0); N_NIMCALL(void, genericAssign)(void* dest0, void* src0, TNimType* mt0); N_NIMCALL(void, localerror_194085_155036129)(Tlineinfo189336 info0, NimStringDesc* arg0); N_NIMCALL(NIM_BOOL, issimpleconst_530311_839829468)(Ttype290840* typ0); N_NIMCALL(void, putintodest_548468_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0, Tstorageloc290812 s0); N_NIMCALL(void, gencomplexconst_556249_839829468)(Tcproc527021* p0, Tsym290834* sym0, Tloc290816* d0); N_NIMCALL(void, requestconstimpl_537240_839829468)(Tcproc527021* p0, Tsym290834* sym0); N_NIMCALL(Ropeobj177006*, genconstexpr_552849_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, tobitset_338001_452470228)(Tnode290802* s0, Tbitset337004** b0); N_NIMCALL(Ropeobj177006*, genrawsetdata_547629_839829468)(Tbitset337004* cs0, NI size0); N_NIMCALL(NimStringDesc*, nsuToHex)(NI64 x0, NI len0); N_NIMCALL(NI64, bitsettoword_547578_839829468)(Tbitset337004* s0, NI size0); N_NIMCALL(Ropeobj177006*, genconstseq_557371_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* t0); N_NIMCALL(void, appcg_530640_839829468)(Tcgen527027* m0, Tcfilesection527005 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(Ropeobj177006*, genconstsimplelist_557299_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Ropeobj177006*, gennamedconstexpr_557284_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, accessthreadlocalvar_530945_839829468)(Tcproc527021* p0, Tsym290834* s0); static N_INLINE(Ropeobj177006**, procsec_527194_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0); static N_INLINE(NIM_BOOL, isemptytype_295441_850551059)(Ttype290840* t0); N_NIMCALL(void, putdataintodest_548436_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0); N_NIMCALL(void, genlinedir_530823_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(Ropeobj177006*, sourceline_190065_155036129)(Tlineinfo189336 i0); N_NIMCALL(NIM_BOOL, freshlineinfo_530818_839829468)(Tcproc527021* p0, Tlineinfo189336 info0); N_NIMCALL(void, genmagicexpr_555033_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0); N_NIMCALL(void, genandor_552311_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0); N_NIMCALL(Ropeobj177006*, getlabel_537217_839829468)(Tcproc527021* p0); N_NIMCALL(void, fixlabel_537230_839829468)(Tcproc527021* p0, Ropeobj177006* labl0); N_NIMCALL(void, unaryarith_550646_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0); N_NIMCALL(void, unaryarithoverflow_549633_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0); N_NIMCALL(void, binaryfloatarith_554729_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0); N_NIMCALL(void, binaryarith_549819_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0); N_NIMCALL(void, geneqproc_550214_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, binaryarithoverflow_549262_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0); N_NIMCALL(Ropeobj177006*, binaryarithoverflowraw_549235_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816* a0, Tloc290816* b0, NimStringDesc* frmt0); N_NIMCALL(Ropeobj177006*, rdcharloc_536227_839829468)(Tloc290816* a0); N_NIMCALL(NI64, lastord_318004_3876443242)(Ttype290840* t0); N_NIMCALL(void, genrepr_553339_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(Ropeobj177006*, lenfield_537305_839829468)(Tcproc527021* p0); N_NIMCALL(void, gcusage_552439_839829468)(Tnode290802* n0); N_NIMCALL(void, message_194095_155036129)(Tlineinfo189336 info0, Tmsgkind189002 msg0, NimStringDesc* arg0); N_NIMCALL(NimStringDesc*, rendertree_309044_382274130)(Tnode290802* n0, Trenderflag309004Set renderflags0); N_NIMCALL(void, gengettypeinfo_553383_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genswap_553638_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, unaryexpr_549209_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, binarystmt_548501_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genstrconcat_552452_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genstrappend_552554_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genseqelemappend_552683_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genstrequals_554667_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, binaryexpr_548549_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genisnil_550620_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, gendollar_553391_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genof_553331_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genof_553201_839829468)(Tcproc527021* p0, Tnode290802* x0, Ttype290840* typ0, Tloc290816* d0); N_NIMCALL(void, globalerror_194071_155036129)(Tlineinfo189336 info0, Tmsgkind189002 msg0, NimStringDesc* arg0); N_NIMCALL(Ropeobj177006*, genofhelper_553140_839829468)(Tcproc527021* p0, Ttype290840* dest0, Ropeobj177006* a0); N_NIMCALL(void, gennew_552782_839829468)(Tcproc527021* p0, Tnode290802* e0); N_NIMCALL(void, rawgennew_552741_839829468)(Tcproc527021* p0, Tloc290816* a0, Ropeobj177006* sizeexpr_552745_839829468); N_NIMCALL(void, gennewfinalize_553111_839829468)(Tcproc527021* p0, Tnode290802* e0); N_NIMCALL(void, gennewseq_552824_839829468)(Tcproc527021* p0, Tnode290802* e0); N_NIMCALL(void, gennewseqaux_552795_839829468)(Tcproc527021* p0, Tloc290816* dest0, Ropeobj177006* length0); N_NIMCALL(void, gennewseqofcap_552836_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, gensomecast_554481_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(Ropeobj177006*, getclosuretype_533685_839829468)(Tcgen527027* m0, Ttype290840* t0, Tclosuretypekind533681 kind0); N_NIMCALL(void, genord_554475_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, unaryexprchar_549222_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genarraylen_553415_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0); N_NIMCALL(void, unarystmt_548527_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, gensetlengthstr_553632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, gensetlengthseq_553500_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, gensetop_554419_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0); N_NIMCALL(void, binarystmtinexcl_553858_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(Ropeobj177006*, rdsetelemloc_553662_839829468)(Tloc290816* a0, Ttype290840* settype0); N_NIMCALL(void, binaryexprchar_548809_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, geninop_554009_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, fewcmps_553803_839829468)(Tnode290802* s0); N_NIMCALL(void, geninexpraux_551496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0); N_NIMCALL(void, binaryexprin_553837_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0, NimStringDesc* frmt0); N_NIMCALL(void, gencall_541632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genclosurecall_538452_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0); N_NIMCALL(Ropeobj177006*, genarg_537787_839829468)(Tcproc527021* p0, Tnode290802* n_537790_839829468, Tsym290834* param0, Tnode290802* call0); static N_INLINE(Ropeobj177006*, genargstringtocstring_537776_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Ropeobj177006*, openarrayloc_537665_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Tnode290802*, skipconv_326882_3876443242)(Tnode290802* n0); N_NIMCALL(Tmagic290524, getmagic_316502_2616423590)(Tnode290802* op0); N_NIMCALL(Ropeobj177006*, genargnoparam_537938_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Ropeobj177006*, getrawproctype_538459_839829468)(Tcproc527021* p0, Ttype290840* t0); N_NIMCALL(NIM_BOOL, leftappearsonrightside_537329_839829468)(Tnode290802* le0, Tnode290802* ri0); N_NIMCALL(Tanalysisresult471003, ispartof_471340_788060399)(Tnode290802* a0, Tnode290802* b0); static N_INLINE(NIM_BOOL, hasnoinit_537383_839829468)(Tnode290802* call0); N_NIMCALL(void, resetloc_536350_839829468)(Tcproc527021* p0, Tloc290816* loc0); N_NIMCALL(Ropeobj177006*, addcomma_538464_839829468)(Ropeobj177006* r0); N_NIMCALL(void, geninfixcall_539929_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, contains_109056_4286263276)(NimStringDesc* s0, char136Set chars0); N_NIMCALL(Ropeobj177006*, genpatterncall_539699_839829468)(Tcproc527021* p0, Tnode290802* ri_539702_839829468, NimStringDesc* pat0, Ttype290840* typ_539704_839829468); N_NIMCALL(Ropeobj177006*, genotherarg_537277_839829468)(Tcproc527021* p0, Tnode290802* ri0, NI i0, Ttype290840* typ0); N_NIMCALL(Ropeobj177006*, genthisarg_539475_839829468)(Tcproc527021* p0, Tnode290802* ri_539478_839829468, NI i0, Ttype290840* typ0); N_NIMCALL(Tnode290802*, skipaddrderef_539433_839829468)(Tnode290802* node0); N_NIMCALL(void, fixupcall_537410_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0, Ropeobj177006* callee0, Ropeobj177006* params0); N_NIMCALL(void, gennamedparamcall_540616_839829468)(Tcproc527021* p0, Tnode290802* ri0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, contains_109046_4286263276)(NimStringDesc* s0, NIM_CHAR c0); N_NIMCALL(void, genprefixcall_537960_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0); static N_INLINE(void, poststmtactions_530942_839829468)(Tcproc527021* p0); N_NIMCALL(void, genreset_552731_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, genecho_552369_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(NimStringDesc*, nsuRepeatStr)(NimStringDesc* s0, NI n0); N_NIMCALL(void, genarrtoseq_553046_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0); N_NIMCALL(void, genseqconstr_553004_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0); N_NIMCALL(void, localerror_194080_155036129)(Tlineinfo189336 info0, Tmsgkind189002 msg0, NimStringDesc* arg0); N_NIMCALL(Tnode290802*, wrapprocforspawn_433501_2218250499)(Tsym290834* owner0, Tnode290802* spawnexpr0, Ttype290840* rettype0, Tnode290802* barrier0, Tnode290802* dest0); N_NIMCALL(Tnode290802*, liftparallel_476822_1773027539)(Tsym290834* owner0, Tnode290802* n0); N_NIMCALL(void, gendeepcopy_548374_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0); N_NIMCALL(NIM_BOOL, isdeepconstexpr_316566_2616423590)(Tnode290802* n0); N_NIMCALL(Ropeobj177006*, gensetnode_547664_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, gensetconstr_555496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(NimStringDesc*, nimInt64ToStr)(NI64 x0); N_NIMCALL(void, exprcomplexconst_556684_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genarrayconstr_556207_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, handleconstexpr_552853_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, gentupleconstr_555618_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genobjconstr_552903_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(Tsym290834*, lookupfieldagain_551154_839829468)(Tcproc527021* p0, Ttype290840* ty_551157_839829468, Tsym290834* field0, Ropeobj177006** r0); N_NIMCALL(void, genfieldcheck_551504_839829468)(Tcproc527021* p0, Tnode290802* e0, Ropeobj177006* obj0, Tsym290834* field0, Ttype290840* origty0); N_NIMCALL(Tnode290802*, newstrnode_291677_850551059)(Tnodekind290020 kind0, NimStringDesc* strval0); N_NIMCALL(void, gencast_554538_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genconv_554633_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, comparetypes_324214_3876443242)(Ttype290840* x0, Ttype290840* y0, Tdistinctcompare322427 cmp0, Ttypecmpflag322429Set flags0); N_NIMCALL(void, genaddr_551051_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); static N_INLINE(NIM_BOOL, iscppref_550807_839829468)(Tcproc527021* p0, Ttype290840* typ0); N_NIMCALL(void, genbracketexpr_552277_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genarrayelem_552093_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, isconstexpr_316510_2616423590)(Tnode290802* n0); N_NIMCALL(void, genopenarrayelem_552169_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0); N_NIMCALL(void, genseqelem_552205_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0); N_NIMCALL(void, gencstringelem_552144_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0); N_NIMCALL(void, gentupleelem_551124_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genderef_541921_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NIM_BOOL enforcederef0); N_NIMCALL(void, genrecordfield_551448_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(Ttype290840*, genrecordfieldaux_551096_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tloc290816* a0); N_NIMCALL(void, gencheckedrecordfield_552046_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0); N_NIMCALL(void, genblock_544083_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(NI, startblock_541978_839829468)(Tcproc527021* p0, NimStringDesc* start0, Ropeobj177006** args0, NI args0Len0); N_NIMCALL(void, endblock_542060_839829468)(Tcproc527021* p0); N_NIMCALL(void, endblock_542035_839829468)(Tcproc527021* p0, Ropeobj177006* blockend0); N_NIMCALL(Ropeobj177006*, blockbody_542025_839829468)(Tblock527019* b0); N_NIMCALL(void, genstmtlistexpr_556402_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genif_542982_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, downconv_556581_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(NI, inheritancediff_324252_3876443242)(Ttype290840* a0, Ttype290840* b0); N_NIMCALL(void, upconv_556431_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genrangechck_554591_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* magic0); N_NIMCALL(void, convstrtocstr_554643_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, convcstrtostr_554655_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, genclosure_555836_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); static N_INLINE(NIM_BOOL, isconstclosure_555810_839829468)(Tnode290802* n0); static N_INLINE(NIM_BOOL, isroutine_295324_850551059)(Tsym290834* s0); N_NIMCALL(void, genwhilestmt_543985_839829468)(Tcproc527021* p0, Tnode290802* t0); static N_INLINE(Ropeobj177006*, assignlabel_542020_839829468)(Tblock527019* b0); N_NIMCALL(NIM_BOOL, stmtscontainpragma_526083_2036603609)(Tnode290802* n0, Tspecialword273003 w0); N_NIMCALL(void, gencomputedgoto_543744_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, genvarstmt_542854_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, gensinglevar_542276_839829468)(Tcproc527021* p0, Tnode290802* a0); N_NIMCALL(void, gengotovar_542258_839829468)(Tcproc527021* p0, Tnode290802* value0); N_NIMCALL(void, assignglobalvar_536819_839829468)(Tcproc527021* p0, Tsym290834* s0); N_NIMCALL(void, varindynamiclib_536812_839829468)(Tcgen527027* m0, Tsym290834* sym0); N_NIMCALL(void, registergcroot_541762_839829468)(Tcproc527021* p0, Tsym290834* v0); N_NIMCALL(Ropeobj177006*, gentraverseprocforglobal_536032_839829468)(Tcgen527027* m0, Tsym290834* s0); static N_INLINE(NIM_BOOL, isassignedimmediately_541781_839829468)(Tnode290802* n0); N_NIMCALL(NIM_BOOL, containshiddenpointer_318120_3876443242)(Ttype290840* typ0); static N_INLINE(void, loadinto_541928_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* a0); N_NIMCALL(void, genasgncall_541695_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0); N_NIMCALL(void, genclosurevar_542832_839829468)(Tcproc527021* p0, Tnode290802* a0); N_NIMCALL(void, genvartuple_541794_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Tnode290802*, lowertupleunpacking_431037_2218250499)(Tnode290802* n0, Tsym290834* owner0); N_NIMCALL(void, genconststmt_542909_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(NIM_BOOL, containscompiletimeonly_326721_3876443242)(Ttype290840* t0); static N_INLINE(NIM_BOOL, emitlazily_530248_839829468)(Tsym290834* s0); N_NIMCALL(void, gencase_545827_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0); N_NIMCALL(void, genstringcase_545417_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0); N_NIMCALL(NI, nextpoweroftwo_100629_1009420244)(NI x0); N_NIMCALL(void, gencasestringbranch_545100_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816* e0, Ropeobj177006* labl0, Ropeobj177006** branches0, NI branches0Len0); N_NIMCALL(NI64, hashstring_526100_2036603609)(NimStringDesc* s0); N_NIMCALL(Ropeobj177006*, gencasesecondpass_544965_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NI labid0, NI until0); N_NIMCALL(void, exprblock_542103_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(void, gencasegeneric_545087_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0); N_NIMCALL(Ropeobj177006*, genifforcaseuntil_545021_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc290816* a0); N_NIMCALL(void, gencasegenericbranch_544910_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816* e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj177006* labl0); N_NIMCALL(void, gengotoforcase_543673_839829468)(Tcproc527021* p0, Tnode290802* casestmt0); N_NIMCALL(void, genordinalcase_545725_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0); N_NIMCALL(NI, ifswitchsplitpoint_545616_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(NIM_BOOL, branchhastoobigrange_545576_839829468)(Tnode290802* b0); N_NIMCALL(void, genreturnstmt_543617_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(void, blockleaveactions_543442_839829468)(Tcproc527021* p0, NI howmanytrys0, NI howmanyexcepts0); static N_INLINE(Tnode290802*, pop_316246_1689653243)(Tnodeseq290796** s0); N_NIMCALL(void, genbreakstmt_544444_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(void, genasgn_547239_839829468)(Tcproc527021* p0, Tnode290802* e0, NIM_BOOL fastasgn0); N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_547080_839829468)(Tcproc527021* p0, Tnode290802* asgn0); N_NIMCALL(void, asgnfielddiscriminant_547209_839829468)(Tcproc527021* p0, Tnode290802* e0); N_NIMCALL(void, gendiscriminantcheck_547144_839829468)(Tcproc527021* p0, Tloc290816* a0, Tloc290816* tmp0, Ttype290840* objtype0, Tsym290834* field0); N_NIMCALL(Ropeobj177006*, discriminatortabledecl_534094_839829468)(Tcgen527027* m0, Ttype290840* objtype0, Tsym290834* d0); N_NIMCALL(void, genasmstmt_546659_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(Ropeobj177006*, genasmoremitstmt_546529_839829468)(Tcproc527021* p0, Tnode290802* t0, NIM_BOOL isasmstmt0); N_NIMCALL(NimStringDesc*, resizeString)(NimStringDesc* dest0, NI addlen0); N_NIMCALL(void, gentrycpp_545866_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0); static N_INLINE(void, gensimpleblock_542095_839829468)(Tcproc527021* p0, Tnode290802* stmts0); N_NIMCALL(void, gentry_546114_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0); N_NIMCALL(NIM_BOOL, isdefined_198011_1967573533)(NimStringDesc* symbol0); N_NIMCALL(void, line_530695_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* r0); static N_INLINE(Ropeobj177006*, pop_177530_1689653243)(TY189350** s0); N_NIMCALL(void, genraisestmt_544828_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(NimStringDesc*, getraisefrmt_544824_839829468)(Tcproc527021* p0); N_NIMCALL(void, gentypesection_536184_839829468)(Tcgen527027* m0, Tnode290802* n0); N_NIMCALL(void, genpragma_547039_839829468)(Tcproc527021* p_547041_839829468, Tnode290802* n0); N_NIMCALL(Tspecialword273003, whichpragma_316911_2616423590)(Tnode290802* n0); N_NIMCALL(void, genemit_546839_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(Tcfilesection527005, determinesection_546819_839829468)(Tnode290802* n0); N_NIMCALL(NIM_BOOL, nsuStartsWith)(NimStringDesc* s0, NimStringDesc* prefix0); N_NIMCALL(void, genbreakpoint_546862_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(void, genwatchpoint_547016_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(Tsym290834*, skipgenericowner_295280_850551059)(Tsym290834* s0); N_NIMCALL(void, genparforstmt_544208_839829468)(Tcproc527021* p0, Tnode290802* t0); N_NIMCALL(void, genstate_542117_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, gengotostate_542144_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, genbreakstate_542229_839829468)(Tcproc527021* p0, Tnode290802* n0); N_NIMCALL(void, registermoduletomain_560243_839829468)(Tsym290834* m0); N_NIMCALL(Ropeobj177006*, getinitname_560235_839829468)(Tsym290834* m0); N_NIMCALL(Ropeobj177006*, getsomeinitname_559904_839829468)(Tsym290834* m0, NimStringDesc* suffix0); N_NIMCALL(Ropeobj177006*, getdatinitname_560239_839829468)(Tsym290834* m0); N_NIMCALL(Tnode290802*, generatemethoddispatchers_430151_3853300031)(void); N_NIMCALL(void, genmainproc_559729_839829468)(Tcgen527027* m0); N_NIMCALL(Ropeobj177006*, genfilenames_559688_839829468)(Tcgen527027* m0); N_NIMCALL(void, finishmodule_561420_839829468)(Tcgen527027* m0); N_NIMCALL(void, updatecachedmodule_561813_839829468)(Tcgen527027* m0); N_NIMCALL(NIM_BOOL, mergerequired_528832_2760143328)(Tcgen527027* m0); N_NIMCALL(void, mergefiles_529241_2760143328)(NimStringDesc* cfilename0, Tcgen527027* m0); N_NIMCALL(void, geninitcode_560286_839829468)(Tcgen527027* m0); N_NIMCALL(Ropeobj177006*, gensectionstart_528081_2760143328)(Tcprocsection527011 ps0); N_NIMCALL(Ropeobj177006*, gensectionend_528116_2760143328)(Tcprocsection527011 ps0); N_NIMCALL(Ropeobj177006*, gensectionstart_528015_2760143328)(Tcfilesection527005 fs0); N_NIMCALL(Ropeobj177006*, gensectionend_528050_2760143328)(Tcfilesection527005 fs0); N_NIMCALL(void, finishtypedescriptions_533842_839829468)(Tcgen527027* m0); N_NIMCALL(Ropeobj177006*, genmodule_560491_839829468)(Tcgen527027* m0, NimStringDesc* cfile0); N_NIMCALL(Ropeobj177006*, getfileheader_559683_839829468)(NimStringDesc* cfile0); N_NIMCALL(Ropeobj177006*, getcopyright_559665_839829468)(NimStringDesc* cfile0); N_NIMCALL(NimStringDesc*, getcompilecfilecmd_272284_2528170400)(NimStringDesc* cfilename0, NIM_BOOL isexternal0); static N_INLINE(void, addinttypes_559659_839829468)(Ropeobj177006** result0); N_NIMCALL(Ropeobj177006*, genmergeinfo_528203_2760143328)(Tcgen527027* m0); N_NIMCALL(void, generatethreadlocalstorage_536717_839829468)(Tcgen527027* m0); N_NIMCALL(void, generateheaders_558104_839829468)(Tcgen527027* m0); N_NIMCALL(NimStringDesc*, nsuReplaceChar)(NimStringDesc* s0, NIM_CHAR sub0, NIM_CHAR by0); N_NIMCALL(void, writerope_177836_2381377266)(Ropeobj177006* head0, NimStringDesc* filename0, NIM_BOOL usewarning0); N_NIMCALL(void, addfiletocompile_271863_2528170400)(NimStringDesc* filename0); N_NIMCALL(void, addfiletolink_271872_2528170400)(NimStringDesc* filename0); N_NIMCALL(void, writemodule_561637_839829468)(Tcgen527027* m0, NIM_BOOL pending0); N_NIMCALL(void, generatethreadvarssize_536771_839829468)(Tcgen527027* m0); N_NIMCALL(NIM_BOOL, shouldrecompile_561621_839829468)(Ropeobj177006* code0, NimStringDesc* cfile0); N_NIMCALL(NimStringDesc*, toobjfile_271859_2528170400)(NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, writeropeifnotequal_178511_2381377266)(Ropeobj177006* r0, NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, nosexistsFile)(NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, nosfileNewer)(NimStringDesc* a0, NimStringDesc* b0); N_NIMCALL(void, writemapping_272789_2528170400)(Ropeobj177006* gsymbolmapping0); N_NIMCALL(void, writeheader_561149_839829468)(Tcgen527027* m0); N_NIMCALL(void, nossplitFile)(NimStringDesc* path0, TY124315* Result); N_NIMCALL(void, resetmodule_560763_839829468)(Tcgen527027* m0); N_NIMCALL(void, nullify_560833_839829468)(Ropeobj177006** arr0); N_NIMCALL(void, nullify_560858_839829468)(Ropeobj177006** arr0); STRING_LITERAL(T839829468_4, "\011", 1); STRING_LITERAL(T839829468_10, "compiler/cgen.nim", 17); NIM_CONST TY201018 T839829468_9 = {((NimStringDesc*) &T839829468_10), ((NI) 1158)} ; STRING_LITERAL(T839829468_11, "T", 1); STRING_LITERAL(T839829468_12, "_", 1); STRING_LITERAL(T839829468_13, "added pending module twice: ", 28); STRING_LITERAL(T839829468_14, ".h", 2); STRING_LITERAL(T839829468_15, ".cpp", 4); STRING_LITERAL(T839829468_16, ".m", 2); STRING_LITERAL(T839829468_17, ".c", 2); STRING_LITERAL(T839829468_18, "0", 1); STRING_LITERAL(T839829468_19, "$", 1); STRING_LITERAL(T839829468_20, "ropes: invalid format string $", 30); STRING_LITERAL(T839829468_21, "$N#line $2 $1$N", 15); STRING_LITERAL(T839829468_22, "N_LIB_IMPORT ", 13); STRING_LITERAL(T839829468_23, "N_LIB_EXPORT ", 13); STRING_LITERAL(T839829468_24, "static ", 7); STRING_LITERAL(T839829468_25, "mapType", 7); STRING_LITERAL(T839829468_26, "void", 4); STRING_LITERAL(T839829468_27, "getTypeDescAux: t == nil", 24); STRING_LITERAL(T839829468_28, "TY", 2); STRING_LITERAL(T839829468_29, "getTypeName: ", 13); STRING_LITERAL(T839829468_30, "void*", 5); STRING_LITERAL(T839829468_31, "NimStringDesc", 13); STRING_LITERAL(T839829468_32, "NimStringDesc*", 14); STRING_LITERAL(T839829468_33, "NCSTRING", 8); STRING_LITERAL(T839829468_34, "NIM_BOOL", 8); STRING_LITERAL(T839829468_35, "NIM_CHAR", 8); STRING_LITERAL(T839829468_36, "NI", 2); STRING_LITERAL(T839829468_37, "NI8", 3); STRING_LITERAL(T839829468_38, "NI16", 4); STRING_LITERAL(T839829468_39, "NI32", 4); STRING_LITERAL(T839829468_40, "NI64", 4); STRING_LITERAL(T839829468_41, "NF", 2); STRING_LITERAL(T839829468_42, "NF32", 4); STRING_LITERAL(T839829468_43, "NF64", 4); STRING_LITERAL(T839829468_44, "NF128", 5); STRING_LITERAL(T839829468_45, "NU", 2); STRING_LITERAL(T839829468_46, "NU8", 3); STRING_LITERAL(T839829468_47, "NU16", 4); STRING_LITERAL(T839829468_48, "NU32", 4); STRING_LITERAL(T839829468_49, "NU64", 4); NIM_CONST TY531943 Numericaltypetostr_531941_839829468 = {((NimStringDesc*) &T839829468_36), ((NimStringDesc*) &T839829468_37), ((NimStringDesc*) &T839829468_38), ((NimStringDesc*) &T839829468_39), ((NimStringDesc*) &T839829468_40), ((NimStringDesc*) &T839829468_41), ((NimStringDesc*) &T839829468_42), ((NimStringDesc*) &T839829468_43), ((NimStringDesc*) &T839829468_44), ((NimStringDesc*) &T839829468_45), ((NimStringDesc*) &T839829468_46), ((NimStringDesc*) &T839829468_47), ((NimStringDesc*) &T839829468_48), ((NimStringDesc*) &T839829468_49)} ; STRING_LITERAL(T839829468_50, "tyStatic for getSimpleTypeDesc", 30); STRING_LITERAL(T839829468_51, "cannot generate C type for: ", 28); STRING_LITERAL(T839829468_52, "&", 1); STRING_LITERAL(T839829468_53, "*", 1); STRING_LITERAL(T839829468_54, "$1 $2;$n", 8); STRING_LITERAL(T839829468_55, "typedef $1 $2 $2;$n", 19); STRING_LITERAL(T839829468_56, "union", 5); STRING_LITERAL(T839829468_57, "struct", 6); STRING_LITERAL(T839829468_58, "getTypeForward(", 15); STRING_LITERAL(T839829468_59, "typedef NI32 $1;$n", 18); STRING_LITERAL(T839829468_60, "typedef NU8 $1;$n", 17); STRING_LITERAL(T839829468_61, "typedef NU16 $1;$n", 18); STRING_LITERAL(T839829468_62, "typedef NI64 $1;$n", 18); STRING_LITERAL(T839829468_63, "getTypeDescAux: enum", 20); STRING_LITERAL(T839829468_64, "typedef $1_PTR($2, $3) $4;$n", 28); STRING_LITERAL(T839829468_65, "N_NIMCALL", 9); STRING_LITERAL(T839829468_66, "N_STDCALL", 9); STRING_LITERAL(T839829468_67, "N_CDECL", 7); STRING_LITERAL(T839829468_68, "N_SAFECALL", 10); STRING_LITERAL(T839829468_69, "N_SYSCALL", 9); STRING_LITERAL(T839829468_70, "N_INLINE", 8); STRING_LITERAL(T839829468_71, "N_NOINLINE", 10); STRING_LITERAL(T839829468_72, "N_FASTCALL", 10); STRING_LITERAL(T839829468_73, "N_CLOSURE", 9); STRING_LITERAL(T839829468_74, "N_NOCONV", 8); NIM_CONST TY290016 Callingconvtostr_531587_839829468 = {((NimStringDesc*) &T839829468_65), ((NimStringDesc*) &T839829468_66), ((NimStringDesc*) &T839829468_67), ((NimStringDesc*) &T839829468_68), ((NimStringDesc*) &T839829468_69), ((NimStringDesc*) &T839829468_70), ((NimStringDesc*) &T839829468_71), ((NimStringDesc*) &T839829468_72), ((NimStringDesc*) &T839829468_73), ((NimStringDesc*) &T839829468_74)} ; STRING_LITERAL(T839829468_75, "typedef struct {$nN_NIMCALL_PTR($2, ClPrc) $3;$nvoid* ClEnv;$n}" " $1;$n", 69); STRING_LITERAL(T839829468_76, "struct $2 : #TGenericSeq {$n", 28); STRING_LITERAL(T839829468_77, "struct $2 {$n #TGenericSeq Sup;$n", 34); STRING_LITERAL(T839829468_78, " $1 data[SEQ_DECL_SIZE];$n};$n", 31); STRING_LITERAL(T839829468_79, "TGenericSeq", 11); STRING_LITERAL(T839829468_80, "typedef $1 $2[$3];$n", 20); STRING_LITERAL(T839829468_81, "invalid apostrophe type parameter index", 39); STRING_LITERAL(T839829468_82, "<", 1); STRING_LITERAL(T839829468_83, " COMMA ", 7); STRING_LITERAL(T839829468_84, "> ", 2); extern NIM_CONST TY271427 Cc_271413_2528170400; STRING_LITERAL(T839829468_85, " {$n", 4); STRING_LITERAL(T839829468_86, " {$n#TNimType* m_type;$n", 24); STRING_LITERAL(T839829468_87, " : public $1 {$n", 16); STRING_LITERAL(T839829468_88, " {$n $1 Sup;$n", 15); STRING_LITERAL(T839829468_89, "genRecordFieldsAux", 18); STRING_LITERAL(T839829468_90, "$1.$2", 5); STRING_LITERAL(T839829468_91, "S", 1); STRING_LITERAL(T839829468_92, "struct {", 8); STRING_LITERAL(T839829468_93, "} $1;$n", 7); STRING_LITERAL(T839829468_94, "genRecordFieldsAux(record case branch)", 38); STRING_LITERAL(T839829468_95, "union{$n$1} $2;$n", 17); STRING_LITERAL(T839829468_96, "mangleRecFieldName", 18); STRING_LITERAL(T839829468_97, "$1 $2[SEQ_DECL_SIZE];$n", 23); STRING_LITERAL(T839829468_98, "$1 $2:$3;$n", 11); STRING_LITERAL(T839829468_99, "genRecordFieldsAux()", 20); STRING_LITERAL(T839829468_100, "char dummy;$n", 13); STRING_LITERAL(T839829468_101, "};", 2); STRING_LITERAL(T839829468_102, "$1 $2 {$n", 9); STRING_LITERAL(T839829468_103, "$1 Field$2;$n", 13); STRING_LITERAL(T839829468_104, "char dummy;", 11); STRING_LITERAL(T839829468_105, "Set", 3); STRING_LITERAL(T839829468_106, "typedef NU$2 $1;$n", 18); STRING_LITERAL(T839829468_107, "typedef NU8 $1[$2];$n", 21); STRING_LITERAL(T839829468_108, "getTypeDescAux(", 15); STRING_LITERAL(T839829468_109, "genProcParams", 13); STRING_LITERAL(T839829468_110, ", ", 2); STRING_LITERAL(T839829468_111, " ", 1); STRING_LITERAL(T839829468_112, ", NI $1Len$2", 12); STRING_LITERAL(T839829468_113, " Result", 7); STRING_LITERAL(T839829468_114, "void* ClEnv", 11); STRING_LITERAL(T839829468_115, "...", 3); STRING_LITERAL(T839829468_116, "void)", 5); STRING_LITERAL(T839829468_117, ")", 1); STRING_LITERAL(T839829468_118, "(", 1); STRING_LITERAL(T839829468_119, "$1($2, $3)$4", 12); STRING_LITERAL(T839829468_120, "proc has no result symbol", 25); STRING_LITERAL(T839829468_121, " register", 9); STRING_LITERAL(T839829468_122, " volatile", 9); STRING_LITERAL(T839829468_123, "$1 = $2;$n", 10); STRING_LITERAL(T839829468_124, "(*$1)", 5); STRING_LITERAL(T839829468_125, ";", 1); STRING_LITERAL(T839829468_126, "FR.s[$1].address = (void*)$3; FR.s[$1].typ = $4; FR.s[$1].name " "= $2;$n", 70); STRING_LITERAL(T839829468_127, "NTI$1", 5); STRING_LITERAL(T839829468_128, "(&", 2); STRING_LITERAL(T839829468_129, "TNimType", 8); STRING_LITERAL(T839829468_130, "TNimNode", 8); STRING_LITERAL(T839829468_131, "extern TNimType $1; /* $2 */$n", 30); STRING_LITERAL(T839829468_132, "0", 1); STRING_LITERAL(T839829468_133, "void*", 5); STRING_LITERAL(T839829468_134, "$1.size = sizeof($2);$n$1.kind = $3;$n$1.base = $4;$n", 53); STRING_LITERAL(T839829468_135, "$1.flags = $2;$n", 16); STRING_LITERAL(T839829468_136, "TNimType $1; /* $2 */$n", 23); STRING_LITERAL(T839829468_137, "genTypeInfo(", 12); STRING_LITERAL(T839829468_138, "$1[$2]", 6); STRING_LITERAL(T839829468_139, "static TNimNode* $1[$2];$n", 26); STRING_LITERAL(T839829468_140, "$1[$2] = &$3;$n", 15); STRING_LITERAL(T839829468_141, "$1.kind = 1;$n$1.offset = offsetof($2, Field$3);$n$1.typ = $4;$" "n$1.name = \"Field$3\";$n", 86); STRING_LITERAL(T839829468_142, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n", 45); STRING_LITERAL(T839829468_143, "$1.len = $2; $1.kind = 2;$n", 27); STRING_LITERAL(T839829468_144, "$1.node = &$2;$n", 16); STRING_LITERAL(T839829468_145, "#nimGCvisit((void*)$1, op);$n", 29); STRING_LITERAL(T839829468_146, "N_NIMCALL(void, $1)(void* p, NI op)", 35); STRING_LITERAL(T839829468_147, "$1 a;$n", 7); STRING_LITERAL(T839829468_148, "a = ($1)p;$n", 12); STRING_LITERAL(T839829468_149, "LOC", 3); STRING_LITERAL(T839829468_150, "$1 = ($2)0;$n", 13); STRING_LITERAL(T839829468_151, "<string.h>", 10); STRING_LITERAL(T839829468_152, "memset((void*)$1, 0, sizeof($2));$n", 35); STRING_LITERAL(T839829468_153, ".Sup", 4); STRING_LITERAL(T839829468_154, "$1.m_type = $2;$n", 17); STRING_LITERAL(T839829468_155, "#objectInit($1, $2);$n", 22); STRING_LITERAL(T839829468_156, "for ($1 = 0; $1 < $2->$3; $1++) {$n", 35); STRING_LITERAL(T839829468_157, "len", 3); STRING_LITERAL(T839829468_158, "Sup.len", 7); STRING_LITERAL(T839829468_159, "for ($1 = 0; $1 < $2; $1++) {$n", 31); STRING_LITERAL(T839829468_160, "}$n", 3); STRING_LITERAL(T839829468_161, "$1.Sup", 6); STRING_LITERAL(T839829468_162, "genTraverseProc", 15); STRING_LITERAL(T839829468_163, "switch ($1.$2) {$n", 18); STRING_LITERAL(T839829468_164, "case $1 ... $2:$n", 17); STRING_LITERAL(T839829468_165, "genLiteral: ty is nil", 21); STRING_LITERAL(T839829468_166, "(-2147483647 -1)", 16); STRING_LITERAL(T839829468_167, "IL64($1)", 8); STRING_LITERAL(T839829468_168, "(IL64(-9223372036854775807) - IL64(1))", 38); STRING_LITERAL(T839829468_169, "NIM_TRUE", 8); STRING_LITERAL(T839829468_170, "NIM_FALSE", 9); STRING_LITERAL(T839829468_171, "ULL", 3); STRING_LITERAL(T839829468_172, "(($1) $2)", 9); STRING_LITERAL(T839829468_173, "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n", 45); STRING_LITERAL(T839829468_174, "NIM_NIL", 7); STRING_LITERAL(T839829468_175, "((#NimStringDesc*) NIM_NIL)", 27); STRING_LITERAL(T839829468_176, "((#NimStringDesc*) &$1)", 23); STRING_LITERAL(T839829468_177, "STRING_LITERAL($1, $2, $3);$n", 29); STRING_LITERAL(T839829468_178, "((#NimStringDesc*) &$1$2)", 25); STRING_LITERAL(T839829468_179, "genLiteral(", 11); STRING_LITERAL(T839829468_180, "case $1:$n", 10); STRING_LITERAL(T839829468_181, "default:$n", 10); STRING_LITERAL(T839829468_182, "break;$n", 8); STRING_LITERAL(T839829468_183, "} $n", 4); STRING_LITERAL(T839829468_184, "genTraverseProc()", 17); STRING_LITERAL(T839829468_185, "$1.Field$2", 10); STRING_LITERAL(T839829468_186, "$1.ClEnv", 8); STRING_LITERAL(T839829468_187, "$1->data[$2]", 12); STRING_LITERAL(T839829468_188, "a", 1); STRING_LITERAL(T839829468_189, "(*a)", 4); STRING_LITERAL(T839829468_190, "$1 {$n$2$3$4}$n", 15); STRING_LITERAL(T839829468_191, "$1;$n", 5); STRING_LITERAL(T839829468_192, "$1.marker = $2;$n", 17); STRING_LITERAL(T839829468_193, "$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n", 43); STRING_LITERAL(T839829468_194, "$1.offset = $2;$n", 17); STRING_LITERAL(T839829468_195, "NI $1;$n", 8); STRING_LITERAL(T839829468_196, "static char* NIM_CONST $1[$2] = {$n$3};$n", 41); STRING_LITERAL(T839829468_197, "for ($1 = 0; $1 < $2; $1++) {$n$3[$1+$4].kind = 1;$n$3[$1+$4].o" "ffset = $1;$n$3[$1+$4].name = $5[$1];$n$6[$1] = &$3[$1+$4];$n}$n", 127); STRING_LITERAL(T839829468_198, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n", 61); STRING_LITERAL(T839829468_199, "$1.flags = 1<<2;$n", 18); STRING_LITERAL(T839829468_200, "anonymous obj with discriminator", 32); STRING_LITERAL(T839829468_201, "NimDT_$1_$2", 11); STRING_LITERAL(T839829468_202, "$1.kind = 3;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n" "ame = $5;$n$1.sons = &$6[0];$n$1.len = $7;$n", 107); STRING_LITERAL(T839829468_203, "TNimNode* $1[$2];$n", 19); STRING_LITERAL(T839829468_204, "genObjectFields; nkOfBranch broken", 34); STRING_LITERAL(T839829468_205, "genObjectFields(nkRecCase)", 26); STRING_LITERAL(T839829468_206, "$1.kind = 1;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n" "ame = $5;$n", 74); STRING_LITERAL(T839829468_207, "genObjectFields", 15); STRING_LITERAL(T839829468_208, "$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n", 49); STRING_LITERAL(T839829468_209, "\011return $1;$n", 13); STRING_LITERAL(T839829468_210, "Result", 6); STRING_LITERAL(T839829468_211, "closure generation failed", 25); STRING_LITERAL(T839829468_212, "$1 = ($2) ClEnv;$n", 18); STRING_LITERAL(T839829468_213, "__declspec(noreturn) ", 21); STRING_LITERAL(T839829468_214, "__declspec(naked) ", 18); STRING_LITERAL(T839829468_215, "$N$1 {$n$2$3$4}$N$N", 19); STRING_LITERAL(T839829468_216, "$N$1 {$N", 8); STRING_LITERAL(T839829468_217, "struct {$1} GCFRAME;$n", 22); STRING_LITERAL(T839829468_218, "nimFrame", 8); STRING_LITERAL(T839829468_219, "VarSlot", 7); STRING_LITERAL(T839829468_220, "\011nimfrs($1, $2, $3, $4)$N", 25); STRING_LITERAL(T839829468_221, "\011nimfr($1, $2)$N", 16); STRING_LITERAL(T839829468_222, "\011#nimProfile();$n", 17); STRING_LITERAL(T839829468_223, "{", 1); STRING_LITERAL(T839829468_224, "\011}BeforeRet: ;$n", 16); STRING_LITERAL(T839829468_225, "if (((NU)&GCFRAME) < 4096) #nimGCFrame(&GCFRAME);$n", 51); STRING_LITERAL(T839829468_226, "\011#popFrame();$n", 15); STRING_LITERAL(T839829468_227, "}$N", 3); STRING_LITERAL(T839829468_228, "static void* $1;$n", 18); STRING_LITERAL(T839829468_229, "||", 2); STRING_LITERAL(T839829468_230, "($1 = #nimLoadLibrary((#NimStringDesc*) &$2))$n", 47); STRING_LITERAL(T839829468_231, "if (!($1)) #nimLoadLibraryError((#NimStringDesc*) &$2);$n", 57); STRING_LITERAL(T839829468_232, "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n", 60); STRING_LITERAL(T839829468_233, "loadDynamicLib", 14); STRING_LITERAL(T839829468_234, "Dl_$1", 5); STRING_LITERAL(T839829468_235, "\011$1 = ($2) ($3$4));$n", 21); NIM_CONST TY201018 T839829468_236 = {((NimStringDesc*) &T839829468_10), ((NI) 535)} ; STRING_LITERAL(T839829468_237, "wrong index: ", 13); STRING_LITERAL(T839829468_238, "\011$1 = ($2) #nimGetProcAddr($3, $4);$n", 37); STRING_LITERAL(T839829468_239, "$2 $1;$n", 8); STRING_LITERAL(T839829468_240, "extern ", 7); STRING_LITERAL(T839829468_241, "NIM_THREADVAR ", 14); STRING_LITERAL(T839829468_242, " $1;$n", 6); STRING_LITERAL(T839829468_243, "cgsym: ", 7); STRING_LITERAL(T839829468_244, ": ", 2); STRING_LITERAL(T839829468_245, "extern $1 $2;$n", 15); STRING_LITERAL(T839829468_246, "extern \"C\" ", 11); STRING_LITERAL(T839829468_247, " __attribute__((naked))", 23); STRING_LITERAL(T839829468_248, " __attribute__((noreturn))", 26); STRING_LITERAL(T839829468_249, "#asgnRef((void**) $1, $2);$n", 28); STRING_LITERAL(T839829468_250, "#asgnRefNoCycle((void**) $1, $2);$n", 35); STRING_LITERAL(T839829468_251, "#unsureAsgnRef((void**) $1, $2);$n", 34); STRING_LITERAL(T839829468_252, "#genericSeqAssign($1, $2, $3);$n", 32); STRING_LITERAL(T839829468_253, "$1 = #copyString($2);$n", 23); STRING_LITERAL(T839829468_254, "$3 = $1; $1 = #copyStringRC1($2);$n", 35); STRING_LITERAL(T839829468_255, "if ($1) #nimGCunrefNoCycle($1);$n", 33); STRING_LITERAL(T839829468_256, "#unsureAsgnRef((void**) $1, #copyString($2));$n", 47); STRING_LITERAL(T839829468_257, ".", 1); STRING_LITERAL(T839829468_258, "ClEnv", 5); STRING_LITERAL(T839829468_259, "$1.ClPrc = $2.ClPrc;$n", 22); STRING_LITERAL(T839829468_260, "Field$1", 7); STRING_LITERAL(T839829468_261, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n", 53); STRING_LITERAL(T839829468_262, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n", 50); STRING_LITERAL(T839829468_263, "#genericAssign((void*)$1, (void*)$2, $3);$n", 43); STRING_LITERAL(T839829468_265, "compiler/ccgexprs.nim", 21); NIM_CONST TY201018 T839829468_264 = {((NimStringDesc*) &T839829468_265), ((NI) 320)} ; STRING_LITERAL(T839829468_266, "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 60); STRING_LITERAL(T839829468_267, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len0);$n", 63); STRING_LITERAL(T839829468_268, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n", 45); STRING_LITERAL(T839829468_269, "genAssignment: ", 15); STRING_LITERAL(T839829468_270, "request to generate code for .compileTime proc: ", 48); STRING_LITERAL(T839829468_271, "expr: proc not init ", 20); STRING_LITERAL(T839829468_272, "NIM_CONST $1 $2 = $3;$n", 23); STRING_LITERAL(T839829468_273, "{$n", 3); STRING_LITERAL(T839829468_274, "0x$1,$n", 7); STRING_LITERAL(T839829468_275, "0x$1, ", 6); STRING_LITERAL(T839829468_276, "0x$1}$n", 7); STRING_LITERAL(T839829468_277, "{{$1, $1}", 9); STRING_LITERAL(T839829468_278, ", {", 3); STRING_LITERAL(T839829468_279, ",$n", 3); STRING_LITERAL(T839829468_280, "}", 1); STRING_LITERAL(T839829468_281, "NIM_CONST struct {$n #TGenericSeq Sup;$n $1 data[$2];$n} $3 =" " $4;$n", 69); STRING_LITERAL(T839829468_282, "(($1)&$2)", 9); STRING_LITERAL(T839829468_283, "$1,$n", 5); STRING_LITERAL(T839829468_284, "extern NIM_CONST $1 $2;$n", 25); STRING_LITERAL(T839829468_285, "expr: var not init ", 19); STRING_LITERAL(T839829468_286, "\011NimThreadVars* NimTV;$n", 24); STRING_LITERAL(T839829468_287, "\011NimTV = (NimThreadVars*) #GetThreadLocalVars();$n", 50); STRING_LITERAL(T839829468_288, "NimTV->", 7); STRING_LITERAL(T839829468_289, "expr: temp not init ", 20); STRING_LITERAL(T839829468_290, "expr: param not init ", 21); STRING_LITERAL(T839829468_291, "expr(", 5); STRING_LITERAL(T839829468_292, "); unknown symbol", 17); STRING_LITERAL(T839829468_293, "//", 2); STRING_LITERAL(T839829468_294, "#endb($1, $2);$n", 16); STRING_LITERAL(T839829468_295, "nimln($1, $2);$n", 16); STRING_LITERAL(T839829468_296, "LA", 2); STRING_LITERAL(T839829468_297, "if ($1) goto $2;$n", 18); STRING_LITERAL(T839829468_298, "if (!($1)) goto $2;$n", 21); STRING_LITERAL(T839829468_299, "$1: ;$n", 7); STRING_LITERAL(T839829468_300, "!($1)", 5); STRING_LITERAL(T839829468_301, "$1", 2); STRING_LITERAL(T839829468_302, "($3)((NU$2) ~($1))", 18); STRING_LITERAL(T839829468_303, "-($1)", 5); STRING_LITERAL(T839829468_304, "($1 > 0? ($1) : -($1))", 22); STRING_LITERAL(T839829468_305, "(($3)(NU)(NU8)($1))", 19); STRING_LITERAL(T839829468_306, "(($3)(NU64)(NU8)($1))", 21); STRING_LITERAL(T839829468_307, "(($3)(NU)(NU16)($1))", 20); STRING_LITERAL(T839829468_308, "(($3)(NU64)(NU16)($1))", 22); STRING_LITERAL(T839829468_309, "(($3)(NU64)(NU32)($1))", 22); STRING_LITERAL(T839829468_310, "(($3)(NU64)(NU)($1))", 20); STRING_LITERAL(T839829468_311, "(($3)(NU8)(NU)($1))", 19); STRING_LITERAL(T839829468_312, "(($3)(NU16)(NU)($1))", 20); STRING_LITERAL(T839829468_313, "(($3)(NU32)(NU64)($1))", 22); STRING_LITERAL(T839829468_314, "((double) ($1))", 15); STRING_LITERAL(T839829468_315, "float64ToInt32($1)", 18); STRING_LITERAL(T839829468_316, "float64ToInt64($1)", 18); NIM_CONST TY550655 unarithtab_550653_839829468 = {((NimStringDesc*) &T839829468_300), ((NimStringDesc*) &T839829468_301), ((NimStringDesc*) &T839829468_302), ((NimStringDesc*) &T839829468_301), ((NimStringDesc*) &T839829468_303), ((NimStringDesc*) &T839829468_304), ((NimStringDesc*) &T839829468_305), ((NimStringDesc*) &T839829468_306), ((NimStringDesc*) &T839829468_307), ((NimStringDesc*) &T839829468_308), ((NimStringDesc*) &T839829468_309), ((NimStringDesc*) &T839829468_310), ((NimStringDesc*) &T839829468_311), ((NimStringDesc*) &T839829468_312), ((NimStringDesc*) &T839829468_313), ((NimStringDesc*) &T839829468_314), ((NimStringDesc*) &T839829468_314), ((NimStringDesc*) &T839829468_315), ((NimStringDesc*) &T839829468_316)} ; STRING_LITERAL(T839829468_317, "if ($1 == $2) #raiseOverflow();$n", 33); STRING_LITERAL(T839829468_318, "((NI$2)-($1))", 13); NIM_CONST TY549642 opr_549640_839829468 = {((NimStringDesc*) &T839829468_318), ((NimStringDesc*) &T839829468_303), ((NimStringDesc*) &T839829468_304)} ; STRING_LITERAL(T839829468_319, "(($4)($2) $1 ($4)($3))", 22); STRING_LITERAL(T839829468_320, "+", 1); STRING_LITERAL(T839829468_321, "-", 1); STRING_LITERAL(T839829468_322, "/", 1); NIM_CONST TY554765 opr_554763_839829468 = {((NimStringDesc*) &T839829468_320), ((NimStringDesc*) &T839829468_321), ((NimStringDesc*) &T839829468_53), ((NimStringDesc*) &T839829468_322)} ; STRING_LITERAL(T839829468_323, "#nanCheck($1);$n", 16); STRING_LITERAL(T839829468_324, "#infCheck($1);$n", 16); STRING_LITERAL(T839829468_325, "(($4)($1) + ($4)($2))", 21); STRING_LITERAL(T839829468_326, "(($4)($1) - ($4)($2))", 21); STRING_LITERAL(T839829468_327, "(($4)($1) * ($4)($2))", 21); STRING_LITERAL(T839829468_328, "(($4)($1) / ($4)($2))", 21); STRING_LITERAL(T839829468_329, "($4)((NU$3)($1) >> (NU$3)($2))", 30); STRING_LITERAL(T839829468_330, "($4)((NU$3)($1) << (NU$3)($2))", 30); STRING_LITERAL(T839829468_331, "($4)($1 & $2)", 13); STRING_LITERAL(T839829468_332, "($4)($1 | $2)", 13); STRING_LITERAL(T839829468_333, "($4)($1 ^ $2)", 13); STRING_LITERAL(T839829468_334, "(($1 <= $2) ? $1 : $2)", 22); STRING_LITERAL(T839829468_335, "(($1 >= $2) ? $1 : $2)", 22); STRING_LITERAL(T839829468_336, "($4)((NU$3)($1) + (NU$3)($2))", 29); STRING_LITERAL(T839829468_337, "($4)((NU$3)($1) - (NU$3)($2))", 29); STRING_LITERAL(T839829468_338, "($4)((NU$3)($1) * (NU$3)($2))", 29); STRING_LITERAL(T839829468_339, "($4)((NU$3)($1) / (NU$3)($2))", 29); STRING_LITERAL(T839829468_340, "($4)((NU$3)($1) % (NU$3)($2))", 29); STRING_LITERAL(T839829468_341, "($1 == $2)", 10); STRING_LITERAL(T839829468_342, "($1 <= $2)", 10); STRING_LITERAL(T839829468_343, "($1 < $2)", 9); STRING_LITERAL(T839829468_344, "((NU$3)($1) <= (NU$3)($2))", 26); STRING_LITERAL(T839829468_345, "((NU$3)($1) < (NU$3)($2))", 25); STRING_LITERAL(T839829468_346, "((NU64)($1) <= (NU64)($2))", 26); STRING_LITERAL(T839829468_347, "((NU64)($1) < (NU64)($2))", 25); STRING_LITERAL(T839829468_348, "((NU8)($1) == (NU8)($2))", 24); STRING_LITERAL(T839829468_349, "((NU8)($1) <= (NU8)($2))", 24); STRING_LITERAL(T839829468_350, "((NU8)($1) < (NU8)($2))", 23); STRING_LITERAL(T839829468_351, "($1 != $2)", 10); NIM_CONST TY549828 binarithtab_549826_839829468 = {((NimStringDesc*) &T839829468_325), ((NimStringDesc*) &T839829468_326), ((NimStringDesc*) &T839829468_327), ((NimStringDesc*) &T839829468_328), ((NimStringDesc*) &T839829468_329), ((NimStringDesc*) &T839829468_330), ((NimStringDesc*) &T839829468_331), ((NimStringDesc*) &T839829468_332), ((NimStringDesc*) &T839829468_333), ((NimStringDesc*) &T839829468_334), ((NimStringDesc*) &T839829468_335), ((NimStringDesc*) &T839829468_334), ((NimStringDesc*) &T839829468_335), ((NimStringDesc*) &T839829468_336), ((NimStringDesc*) &T839829468_337), ((NimStringDesc*) &T839829468_338), ((NimStringDesc*) &T839829468_339), ((NimStringDesc*) &T839829468_340), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_344), ((NimStringDesc*) &T839829468_345), ((NimStringDesc*) &T839829468_346), ((NimStringDesc*) &T839829468_347), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_348), ((NimStringDesc*) &T839829468_349), ((NimStringDesc*) &T839829468_350), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_351)} ; STRING_LITERAL(T839829468_352, "($1.ClPrc == $2.ClPrc && $1.ClEnv == $2.ClEnv)", 46); STRING_LITERAL(T839829468_353, "($#)($# + $#)", 13); STRING_LITERAL(T839829468_354, "($#)($# - $#)", 13); STRING_LITERAL(T839829468_355, "($#)($# * $#)", 13); STRING_LITERAL(T839829468_356, "($#)($# / $#)", 13); STRING_LITERAL(T839829468_357, "($#)($# % $#)", 13); NIM_CONST TY549281 opr_549279_839829468 = {((NimStringDesc*) &T839829468_353), ((NimStringDesc*) &T839829468_354), ((NimStringDesc*) &T839829468_355), ((NimStringDesc*) &T839829468_356), ((NimStringDesc*) &T839829468_357), ((NimStringDesc*) &T839829468_353), ((NimStringDesc*) &T839829468_354)} ; STRING_LITERAL(T839829468_358, "((NU8)($1))", 11); STRING_LITERAL(T839829468_359, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n", 43); STRING_LITERAL(T839829468_360, "$# = #addInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_361, "$# = #subInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_362, "$# = #mulInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_363, "$# = #divInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_364, "$# = #modInt64($#, $#);$n", 25); NIM_CONST TY549281 prc64_549274_839829468 = {((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361), ((NimStringDesc*) &T839829468_362), ((NimStringDesc*) &T839829468_363), ((NimStringDesc*) &T839829468_364), ((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361)} ; STRING_LITERAL(T839829468_365, "$# = #addInt($#, $#);$n", 23); STRING_LITERAL(T839829468_366, "$# = #subInt($#, $#);$n", 23); STRING_LITERAL(T839829468_367, "$# = #mulInt($#, $#);$n", 23); STRING_LITERAL(T839829468_368, "$# = #divInt($#, $#);$n", 23); STRING_LITERAL(T839829468_369, "$# = #modInt($#, $#);$n", 23); NIM_CONST TY549281 prc_549269_839829468 = {((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366), ((NimStringDesc*) &T839829468_367), ((NimStringDesc*) &T839829468_368), ((NimStringDesc*) &T839829468_369), ((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366)} ; STRING_LITERAL(T839829468_370, "($#)($#)", 8); STRING_LITERAL(T839829468_371, "#reprInt((NI64)$1)", 18); STRING_LITERAL(T839829468_372, "#reprFloat($1)", 14); STRING_LITERAL(T839829468_373, "#reprBool($1)", 13); STRING_LITERAL(T839829468_374, "#reprChar($1)", 13); STRING_LITERAL(T839829468_375, "#reprEnum((NI)$1, $2)", 21); STRING_LITERAL(T839829468_376, "#reprStr($1)", 12); STRING_LITERAL(T839829468_377, "#reprSet($1, $2)", 16); STRING_LITERAL(T839829468_378, "$1, $1Len0", 10); STRING_LITERAL(T839829468_379, "$1->data, $1->$2", 16); STRING_LITERAL(T839829468_380, "$1, $2", 6); STRING_LITERAL(T839829468_381, "genRepr()", 9); STRING_LITERAL(T839829468_382, "#reprOpenArray($1, $2)", 22); STRING_LITERAL(T839829468_383, "#reprAny($1, $2)", 16); STRING_LITERAL(T839829468_384, "\'repr\' doesn\'t support \'void\' type", 34); STRING_LITERAL(T839829468_385, "($1 - 1)", 8); STRING_LITERAL(T839829468_386, "#subInt($1, 1)", 14); STRING_LITERAL(T839829468_387, "binaryStmt", 10); STRING_LITERAL(T839829468_388, "$1 += $2;$n", 11); STRING_LITERAL(T839829468_389, "$1 -= $2;$n", 11); NIM_CONST TY555052 opr_555050_839829468 = {((NimStringDesc*) &T839829468_388), ((NimStringDesc*) &T839829468_389)} ; NIM_CONST TY555052 fun64_555055_839829468 = {((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361)} ; NIM_CONST TY555052 fun_555060_839829468 = {((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366)} ; STRING_LITERAL(T839829468_390, "#appendChar($1, $2);$n", 22); STRING_LITERAL(T839829468_391, "$1->$2 + ", 9); STRING_LITERAL(T839829468_392, "#appendString($1, $2);$n", 24); STRING_LITERAL(T839829468_393, "$1 = #rawNewString($2$3);$n", 27); STRING_LITERAL(T839829468_394, "$1 = #addChar($1, $2);$n", 24); STRING_LITERAL(T839829468_395, "$1 = #resizeString($1, $2$3);$n", 31); STRING_LITERAL(T839829468_396, "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n", 47); STRING_LITERAL(T839829468_397, "$1 = ($2) #incrSeqV2($1, sizeof($3));$n", 39); STRING_LITERAL(T839829468_398, "$1->data[$1->$2]", 16); STRING_LITERAL(T839829468_399, "++$1->$2;$n", 11); STRING_LITERAL(T839829468_400, "(($1) && ($1)->$2 == 0)", 23); STRING_LITERAL(T839829468_401, "#eqStrings($1, $2)", 18); STRING_LITERAL(T839829468_402, "(#cmpStrings($1, $2) <= 0)", 26); STRING_LITERAL(T839829468_403, "(#cmpStrings($1, $2) < 0)", 25); STRING_LITERAL(T839829468_404, "$1.ClPrc == 0", 13); STRING_LITERAL(T839829468_405, "$1 == 0", 7); STRING_LITERAL(T839829468_406, "#nimIntToStr($1)", 16); STRING_LITERAL(T839829468_407, "#nimInt64ToStr($1)", 18); STRING_LITERAL(T839829468_408, "#nimBoolToStr($1)", 17); STRING_LITERAL(T839829468_409, "#nimCharToStr($1)", 17); STRING_LITERAL(T839829468_410, "#nimFloatToStr($1)", 18); STRING_LITERAL(T839829468_411, "#cstrToNimstr($1)", 17); STRING_LITERAL(T839829468_412, "no \'of\' operator available for pure objects", 43); STRING_LITERAL(T839829468_413, "(($1) && ($2))", 14); STRING_LITERAL(T839829468_414, "$1.m_type == $2", 15); STRING_LITERAL(T839829468_415, "Nim_OfCheck_CACHE", 17); STRING_LITERAL(T839829468_416, "static TNimType* $#[2];$n", 25); STRING_LITERAL(T839829468_417, "#isObjWithCache($#.m_type, $#, $#)", 34); STRING_LITERAL(T839829468_418, "($1)", 4); STRING_LITERAL(T839829468_419, "sizeof($1)", 10); STRING_LITERAL(T839829468_420, "if ($1) #nimGCunref($1);$n", 26); STRING_LITERAL(T839829468_421, "($1) #newObjRC1($2, $3)", 23); STRING_LITERAL(T839829468_422, "($1) #newObj($2, $3)", 20); STRING_LITERAL(T839829468_423, "$1->finalizer = (void*)$2;$n", 28); STRING_LITERAL(T839829468_424, "($1) #newObj($2, sizeof($3))", 28); STRING_LITERAL(T839829468_425, "($1) #newSeqRC1($2, $3)", 23); STRING_LITERAL(T839829468_426, "($1) #newSeq($2, $3)", 20); STRING_LITERAL(T839829468_427, "($1)#nimNewSeqOfCap($2, $3)", 27); STRING_LITERAL(T839829468_428, "((NI)sizeof($1))", 16); STRING_LITERAL(T839829468_429, "(*($1*) ($2))", 13); STRING_LITERAL(T839829468_430, "(($1) ($2))", 11); STRING_LITERAL(T839829468_431, "($1Len0-1)", 10); STRING_LITERAL(T839829468_432, "$1Len0", 6); STRING_LITERAL(T839829468_433, "($1 ? (strlen($1)-1) : -1)", 26); STRING_LITERAL(T839829468_434, "($1 ? strlen($1) : 0)", 21); STRING_LITERAL(T839829468_435, "($1 ? ($1->Sup.len-1) : -1)", 27); STRING_LITERAL(T839829468_436, "($1 ? $1->Sup.len : 0)", 22); STRING_LITERAL(T839829468_437, "($1 ? ($1->len-1) : -1)", 23); STRING_LITERAL(T839829468_438, "($1 ? $1->len : 0)", 18); STRING_LITERAL(T839829468_439, "genArrayLen()", 13); STRING_LITERAL(T839829468_440, "($1->Sup.len)", 13); STRING_LITERAL(T839829468_441, "$1->len", 7); STRING_LITERAL(T839829468_442, "unaryStmt", 9); STRING_LITERAL(T839829468_443, "#nimGCref($1);$n", 16); STRING_LITERAL(T839829468_444, "#nimGCunref($1);$n", 18); STRING_LITERAL(T839829468_445, "$1 = #setLengthStr($1, $2);$n", 29); STRING_LITERAL(T839829468_446, "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n", 54); STRING_LITERAL(T839829468_447, "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n", 46); STRING_LITERAL(T839829468_448, "($1- $2)", 8); STRING_LITERAL(T839829468_449, "$1 |= ((", 8); STRING_LITERAL(T839829468_450, ")1)<<(($2)%(sizeof(", 19); STRING_LITERAL(T839829468_451, ")*8));$n", 8); STRING_LITERAL(T839829468_452, "$1 &= ~(((", 10); STRING_LITERAL(T839829468_453, ")1) << (($2) % (sizeof(", 23); STRING_LITERAL(T839829468_454, ")*8)));$n", 9); STRING_LITERAL(T839829468_455, "#countBits32($1)", 16); STRING_LITERAL(T839829468_456, "#countBits64($1)", 16); STRING_LITERAL(T839829468_457, "(($1 & ~ $2 ==0)&&($1 != $2))", 29); STRING_LITERAL(T839829468_458, "(($1 & ~ $2)==0)", 16); STRING_LITERAL(T839829468_459, "($1 & $2)", 9); STRING_LITERAL(T839829468_460, "($1 | $2)", 9); STRING_LITERAL(T839829468_461, "($1 & ~ $2)", 11); STRING_LITERAL(T839829468_462, "($1 ^ $2)", 9); STRING_LITERAL(T839829468_463, "fewCmps", 7); STRING_LITERAL(T839829468_464, "$1 >= $2 && $1 <= $3", 20); STRING_LITERAL(T839829468_465, "$1 == $2", 8); STRING_LITERAL(T839829468_466, " || ", 4); STRING_LITERAL(T839829468_467, "(($1 &(1U<<((NU)($2)&7U)))!=0)", 30); STRING_LITERAL(T839829468_468, "(($1 &(1U<<((NU)($2)&15U)))!=0)", 31); STRING_LITERAL(T839829468_469, "(($1 &(1U<<((NU)($2)&31U)))!=0)", 31); STRING_LITERAL(T839829468_470, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)", 36); STRING_LITERAL(T839829468_471, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)", 43); STRING_LITERAL(T839829468_472, "genSetOp()", 10); STRING_LITERAL(T839829468_473, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n", 34); STRING_LITERAL(T839829468_474, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n", 36); STRING_LITERAL(T839829468_475, "#cardSet($1, ", 13); STRING_LITERAL(T839829468_476, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == " "0);$n if (!$3) break;}$n", 88); STRING_LITERAL(T839829468_477, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == " "0);$n if (!$3) break;}$nif ($3) $3 = (memcmp($4, $5, $2) != 0);" "$n", 129); STRING_LITERAL(T839829468_478, "|", 1); STRING_LITERAL(T839829468_479, "& ~", 3); STRING_LITERAL(T839829468_480, "^", 1); NIM_CONST TY554428 lookupopr_554426_839829468 = {((NimStringDesc*) &T839829468_476), ((NimStringDesc*) &T839829468_477), ((NimStringDesc*) &T839829468_52), ((NimStringDesc*) &T839829468_478), ((NimStringDesc*) &T839829468_479), ((NimStringDesc*) &T839829468_480)} ; STRING_LITERAL(T839829468_481, "(memcmp($1, $2, ", 16); STRING_LITERAL(T839829468_482, ")==0)", 5); STRING_LITERAL(T839829468_483, "for ($1 = 0; $1 < $2; $1++) $n $3[$1] = $4[$1] $6 $5[$1];$n", 60); STRING_LITERAL(T839829468_484, "genSetOp", 8); STRING_LITERAL(T839829468_485, "$1->data", 8); STRING_LITERAL(T839829468_486, "($1)+($2), ($3)-($2)+1", 22); STRING_LITERAL(T839829468_487, "(*$1)->data+($2), ($3)-($2)+1", 29); STRING_LITERAL(T839829468_488, "$1->data+($2), ($3)-($2)+1", 26); STRING_LITERAL(T839829468_489, "openArrayLoc: ", 14); STRING_LITERAL(T839829468_490, "", 0); STRING_LITERAL(T839829468_491, "(*$1)->data, (*$1)->$2", 22); STRING_LITERAL(T839829468_492, "$1.ClPrc($3$1.ClEnv)", 20); STRING_LITERAL(T839829468_493, "$1.ClEnv? $1.ClPrc($3$1.ClEnv):(($4)($1.ClPrc))($2)", 51); STRING_LITERAL(T839829468_494, "$1 = 0;$n", 9); STRING_LITERAL(T839829468_495, "#chckNil((void*)$1);$n", 22); STRING_LITERAL(T839829468_496, "#genericReset((void*)$1, $2);$n", 31); STRING_LITERAL(T839829468_497, ";$n", 3); STRING_LITERAL(T839829468_499, "compiler/ccgcalls.nim", 21); NIM_CONST TY201018 T839829468_498 = {((NimStringDesc*) &T839829468_499), ((NI) 423)} ; static NIM_CONST char136Set T839829468_500 = { 0x00, 0x00, 0x00, 0x00, 0x88, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} ; STRING_LITERAL(T839829468_501, "wrong argument count", 20); STRING_LITERAL(T839829468_502, "call expression expected for C++ pattern", 40); NIM_CONST TY201018 T839829468_503 = {((NimStringDesc*) &T839829468_499), ((NI) 328)} ; STRING_LITERAL(T839829468_504, "->", 2); STRING_LITERAL(T839829468_505, ");$n", 4); STRING_LITERAL(T839829468_506, "[", 1); NIM_CONST TY201018 T839829468_507 = {((NimStringDesc*) &T839829468_499), ((NI) 472)} ; STRING_LITERAL(T839829468_508, "varargs for objective C method?", 31); STRING_LITERAL(T839829468_509, "Result: ", 8); STRING_LITERAL(T839829468_510, "];$n", 4); STRING_LITERAL(T839829468_511, "]", 1); NIM_CONST TY201018 T839829468_512 = {((NimStringDesc*) &T839829468_265), ((NI) 925)} ; STRING_LITERAL(T839829468_513, "<stdio.h>", 9); STRING_LITERAL(T839829468_514, ", \"nil\"", 7); STRING_LITERAL(T839829468_515, ", $1? ($1)->data:\"nil\"", 22); STRING_LITERAL(T839829468_516, "printf($1$2);$n", 15); STRING_LITERAL(T839829468_517, "%s", 2); STRING_LITERAL(T839829468_518, "fflush(stdout);$n", 17); STRING_LITERAL(T839829468_519, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n", 45); STRING_LITERAL(T839829468_520, "#genericSeqDeepCopy($1, $2, $3);$n", 34); STRING_LITERAL(T839829468_521, "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 62); STRING_LITERAL(T839829468_522, "genDeepCopy: ", 13); STRING_LITERAL(T839829468_523, "genMagicExpr: ", 14); STRING_LITERAL(T839829468_524, "static NIM_CONST $1 $2 = $3;$n", 30); STRING_LITERAL(T839829468_525, "memset($1, 0, sizeof($1));$n", 28); STRING_LITERAL(T839829468_526, "for ($1 = $3; $1 <= $4; $1++) $n$2[(NU)($1)>>3] |=(1U<<((NU)($1" ")&7U));$n", 72); STRING_LITERAL(T839829468_527, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n", 40); STRING_LITERAL(T839829468_528, "for ($1 = $3; $1 <= $4; $1++) $n$2 |=((", 39); STRING_LITERAL(T839829468_529, ")(1)<<(($1)%(sizeof(", 20); STRING_LITERAL(T839829468_530, "$1 |=((", 7); STRING_LITERAL(T839829468_531, ")(1)<<(($2)%(sizeof(", 20); STRING_LITERAL(T839829468_532, "genCheckedRecordField", 21); STRING_LITERAL(T839829468_533, "genObjConstr", 12); STRING_LITERAL(T839829468_534, "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n", 52); STRING_LITERAL(T839829468_535, "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n", 55); STRING_LITERAL(T839829468_536, "LOC$1.source", 12); STRING_LITERAL(T839829468_537, "union { $1 source; $2 dest; } LOC$3;$n", 38); STRING_LITERAL(T839829468_538, "LOC$#.dest", 10); STRING_LITERAL(T839829468_539, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n", 46); STRING_LITERAL(T839829468_540, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n", 45); STRING_LITERAL(T839829468_541, "$1[($2)- $3]", 12); STRING_LITERAL(T839829468_542, "if ((NU)($1) >= (NU)($2Len0)) #raiseIndexError();$n", 51); STRING_LITERAL(T839829468_543, "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n", 50); STRING_LITERAL(T839829468_544, "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n", 51); STRING_LITERAL(T839829468_545, "genTupleElem", 12); STRING_LITERAL(T839829468_546, ".Field$1", 8); STRING_LITERAL(T839829468_547, "expr(nkBracketExpr, ", 20); STRING_LITERAL(T839829468_548, "genDeref ", 9); STRING_LITERAL(T839829468_549, "genRecordFieldAux", 17); STRING_LITERAL(T839829468_550, "genRecordField 3", 16); STRING_LITERAL(T839829468_551, ".$1", 3); STRING_LITERAL(T839829468_552, "} $1: ;$n", 9); STRING_LITERAL(T839829468_553, "FR.len-=$1;$n", 13); STRING_LITERAL(T839829468_554, "FR.len+=$1;$n", 13); STRING_LITERAL(T839829468_555, "if (!$1) goto $2;$n", 19); STRING_LITERAL(T839829468_556, "goto $1;$n", 10); STRING_LITERAL(T839829468_557, "genIf()", 7); STRING_LITERAL(T839829468_558, "->Sup", 5); STRING_LITERAL(T839829468_559, "$1 = &$2;$n", 11); STRING_LITERAL(T839829468_560, "if ($1) #chckObj($2.m_type, $3);$n", 34); STRING_LITERAL(T839829468_561, "#chckObj($1.m_type, $2);$n", 26); STRING_LITERAL(T839829468_562, "(($1)#$5($2, $3, $4))", 21); STRING_LITERAL(T839829468_563, "chckRangeF", 10); STRING_LITERAL(T839829468_564, "chckRange64", 11); STRING_LITERAL(T839829468_565, "chckRange", 9); STRING_LITERAL(T839829468_566, "CNSTCLOSURE", 11); STRING_LITERAL(T839829468_567, "closure to closure created", 26); STRING_LITERAL(T839829468_568, "$1.ClPrc = $2; $1.ClEnv = $3;$n", 31); STRING_LITERAL(T839829468_569, "while (1) {$n", 13); STRING_LITERAL(T839829468_570, "case statement must be exhaustive for computed goto", 51); STRING_LITERAL(T839829468_571, "case statement has too many cases for computed goto", 51); STRING_LITERAL(T839829468_572, "case statement has to start at 0 for computed goto", 50); STRING_LITERAL(T839829468_573, "no case statement found for computed goto", 41); STRING_LITERAL(T839829468_574, "TMP$1", 5); STRING_LITERAL(T839829468_575, "static void* $#[$#] = {", 23); STRING_LITERAL(T839829468_576, "&&TMP$#, ", 9); STRING_LITERAL(T839829468_577, "&&TMP$#};$n", 11); STRING_LITERAL(T839829468_578, "goto *$#[$#];$n", 15); STRING_LITERAL(T839829468_579, "range notation not available for computed goto", 46); STRING_LITERAL(T839829468_580, "TMP$#:$n", 8); STRING_LITERAL(T839829468_581, "#nimProfile();$n", 16); STRING_LITERAL(T839829468_582, "\'goto\' target must be a literal value", 37); STRING_LITERAL(T839829468_583, "goto NIMSTATE_$#;$n", 19); STRING_LITERAL(T839829468_584, "$1 = ($2*) #nimGetProcAddr($3, $4);$n", 37); STRING_LITERAL(T839829468_585, "$2* $1;$n", 9); STRING_LITERAL(T839829468_586, "#dbgRegisterGlobal($1, &$2, $3);$n", 34); STRING_LITERAL(T839829468_587, "#nimGCvisit((void*)$1, 0);$n", 28); STRING_LITERAL(T839829468_588, "N_NIMCALL(void, $1)(void)", 25); STRING_LITERAL(T839829468_589, "#nimRegisterGlobalMarker($1);$n", 31); STRING_LITERAL(T839829468_590, "$#($#);$n", 9); STRING_LITERAL(T839829468_591, "$# = $#;$n", 10); STRING_LITERAL(T839829468_592, "genVarTuple", 11); STRING_LITERAL(T839829468_593, "genConstStmt", 12); STRING_LITERAL(T839829468_594, "for statement not eliminated", 28); STRING_LITERAL(T839829468_595, "if (#eqStrings($1, $2)) goto $3;$n", 34); STRING_LITERAL(T839829468_596, "switch (#hashString($1) & $2) {$n", 33); STRING_LITERAL(T839829468_597, "case $1: $n$2break;$n", 21); STRING_LITERAL(T839829468_598, "goto LA$1;$n", 12); STRING_LITERAL(T839829468_599, "LA$1: ;$n", 9); STRING_LITERAL(T839829468_600, "if ($1 >= $2 && $1 <= $3) goto $4;$n", 36); STRING_LITERAL(T839829468_601, "if ($1 == $2) goto $3;$n", 24); STRING_LITERAL(T839829468_602, "NIMSTATE_$#:$n", 14); STRING_LITERAL(T839829468_603, "switch ($1) {$n", 15); STRING_LITERAL(T839829468_604, "default: __assume(0);$n", 23); STRING_LITERAL(T839829468_605, "#popSafePoint();$n", 18); STRING_LITERAL(T839829468_606, "#popCurrentException();$n", 25); STRING_LITERAL(T839829468_607, "if ($1.status != 0) #popCurrentException();$n", 45); STRING_LITERAL(T839829468_608, "goto BeforeRet;$n", 17); STRING_LITERAL(T839829468_609, "no loop to break", 16); STRING_LITERAL(T839829468_610, "extern $1", 9); STRING_LITERAL(T839829468_611, "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n", 62); STRING_LITERAL(T839829468_612, "genAsmOrEmitStmt()", 18); STRING_LITERAL(T839829468_613, "\"", 1); STRING_LITERAL(T839829468_614, "\\n\"\015\012", 5); STRING_LITERAL(T839829468_615, "Exception", 9); STRING_LITERAL(T839829468_616, "E_Base", 6); STRING_LITERAL(T839829468_617, "try {$n", 7); STRING_LITERAL(T839829468_618, "} catch (NimException& $1) {$n", 30); STRING_LITERAL(T839829468_619, "#setFrame((TFrame*)&FR);$n", 26); STRING_LITERAL(T839829468_620, "else ", 5); STRING_LITERAL(T839829468_621, "#isObj($1.exp->m_type, $2)", 26); STRING_LITERAL(T839829468_622, "if ($1) ", 8); STRING_LITERAL(T839829468_623, "throw;$n", 8); STRING_LITERAL(T839829468_624, "<setjmp.h>", 10); STRING_LITERAL(T839829468_625, "#TSafePoint $1;$n", 17); STRING_LITERAL(T839829468_626, "#pushSafePoint(&$1);$n", 22); STRING_LITERAL(T839829468_627, "nimStdSetjmp", 12); STRING_LITERAL(T839829468_628, "$1.status = setjmp($1.context);$n", 33); STRING_LITERAL(T839829468_629, "nimSigSetjmp", 12); STRING_LITERAL(T839829468_630, "$1.status = sigsetjmp($1.context, 0);$n", 39); STRING_LITERAL(T839829468_631, "nimRawSetjmp", 12); STRING_LITERAL(T839829468_632, "$1.status = _setjmp($1.context);$n", 34); STRING_LITERAL(T839829468_633, "if ($1.status == 0) {$n", 23); STRING_LITERAL(T839829468_634, "else {$n", 8); STRING_LITERAL(T839829468_635, "else", 4); STRING_LITERAL(T839829468_636, "$1.status = 0;$n", 16); STRING_LITERAL(T839829468_637, "#isObj(#getCurrentException()->Sup.m_type, $1)", 46); STRING_LITERAL(T839829468_638, "#isObj(#getCurrentException()->m_type, $1)", 42); STRING_LITERAL(T839829468_639, "if ($1) {$n", 11); STRING_LITERAL(T839829468_640, "if ($1.status != 0) #reraiseException();$n", 42); STRING_LITERAL(T839829468_641, "#raiseException((#Exception*)$1, $2);$n", 39); STRING_LITERAL(T839829468_642, "#reraiseException();$n", 22); STRING_LITERAL(T839829468_643, "/*TYPESECTION*/", 15); STRING_LITERAL(T839829468_644, "/*VARSECTION*/", 14); STRING_LITERAL(T839829468_645, "/*INCLUDESECTION*/", 18); STRING_LITERAL(T839829468_646, "bp", 2); STRING_LITERAL(T839829468_647, "#dbgRegisterBreakpoint($1, (NCSTRING)$2, (NCSTRING)$3);$n", 57); STRING_LITERAL(T839829468_648, "#dbgRegisterWatchpoint($1, (NCSTRING)$2, $3);$n", 47); STRING_LITERAL(T839829468_649, "#pragma omp parallel for $4$nfor ($1 = $2; $1 <= $3; ++$1)", 58); STRING_LITERAL(T839829468_651, "compiler/ccgstmts.nim", 21); NIM_CONST TY201018 T839829468_650 = {((NimStringDesc*) &T839829468_651), ((NI) 145)} ; STRING_LITERAL(T839829468_652, "STATE$1: ;$n", 12); STRING_LITERAL(T839829468_653, "case -1: goto BeforeRet;$n", 26); STRING_LITERAL(T839829468_654, "case $1: goto STATE$1;$n", 24); STRING_LITERAL(T839829468_655, "if (((NI*) $1)[0] < 0) break;$n", 31); STRING_LITERAL(T839829468_656, "if ((((NI*) $1.ClEnv)[0]) < 0) break;$n", 39); STRING_LITERAL(T839829468_657, "); unknown node kind", 20); NIM_CONST TY201018 T839829468_658 = {((NimStringDesc*) &T839829468_651), ((NI) 1122)} ; STRING_LITERAL(T839829468_659, "Init000", 7); STRING_LITERAL(T839829468_660, "DatInit000", 10); STRING_LITERAL(T839829468_661, "NIM_EXTERNC N_NOINLINE(void, $1)(void);$N", 41); STRING_LITERAL(T839829468_662, "\011$1();$N", 8); STRING_LITERAL(T839829468_663, "N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDECL(void, NimMa" "in)(void) {$N\011void (*volatile inner)();$N\011PreMain();$N\011inner = N" "imMainInner;$N$2\011(*inner)();$N}$N$N", 162); STRING_LITERAL(T839829468_664, "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N " " HINSTANCE hPrevInstance, $N LP" "STR lpCmdLine, int nCmdShow) {$N\011NimMain();$N\011return nim_program" "_result;$N}$N$N", 206); STRING_LITERAL(T839829468_665, "N_LIB_EXPORT N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDEC" "L(void, NimMain)(void) {$N\011void (*volatile inner)();$N\011PreMain()" ";$N\011inner = NimMainInner;$N$2\011(*inner)();$N}$N$N", 175); STRING_LITERAL(T839829468_666, "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N " " LPVOID lpvReserved) {$N\011if(fwdreason == DLL_PROC" "ESS_ATTACH) {$N\011NimMain();$N}$N\011return 1;$N}$N$N", 175); STRING_LITERAL(T839829468_667, "<windows.h>", 11); STRING_LITERAL(T839829468_668, "void NIM_POSIX_INIT NimMainInit(void) {$N\011NimMain();$N}$N$N", 59); STRING_LITERAL(T839829468_669, "int cmdCount;$Nchar** cmdLine;$Nchar** gEnv;$NN_CDECL(void, Nim" "MainInner)(void) {$N$1}$N$NN_CDECL(void, NimMain)(void) {$N\011void" " (*volatile inner)();$N\011PreMain();$N\011inner = NimMainInner;$N$2\011(" "*inner)();$N}$N$N", 208); STRING_LITERAL(T839829468_670, "int main(void) {$N\011NimMain();$N\011return 0;$N}$N$N", 48); STRING_LITERAL(T839829468_671, "int main(int argc, char** args, char** env) {$N\011cmdLine = args;" "$N\011cmdCount = argc;$N\011gEnv = env;$N\011NimMain();$N\011return nim_prog" "ram_result;$N}$N$N", 145); STRING_LITERAL(T839829468_672, "dbgRegisterBreakpoint", 21); STRING_LITERAL(T839829468_673, "dbgRegisterFilename", 19); STRING_LITERAL(T839829468_674, "dbgRegisterFilename($1);$N", 26); STRING_LITERAL(T839829468_675, "\011#initStackBottomWith((void *)&inner);$N", 40); STRING_LITERAL(T839829468_676, "void PreMainInner() {$N\011systemInit000();$N$1$2$3}$N$Nvoid PreMa" "in() {$N\011void (*volatile inner)();$N\011systemDatInit000();$N\011inner" " = PreMainInner;$N$4$5\011(*inner)();$N}$N$N", 168); STRING_LITERAL(T839829468_677, "\011#initThreadVarsEmulation();$N", 30); STRING_LITERAL(T839829468_678, "still forwarded: ", 17); STRING_LITERAL(T839829468_679, "NIM_EXTERNC N_NOINLINE(void, $1)(void) {$N", 42); STRING_LITERAL(T839829468_680, "static #TNimNode $1[$2];$n", 26); STRING_LITERAL(T839829468_681, "static #TNimType $1[$2];$n", 26); STRING_LITERAL(T839829468_682, "\011TFrame FR; FR.len = 0;$N", 25); STRING_LITERAL(T839829468_683, "}$N$N", 5); STRING_LITERAL(T839829468_684, "N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N", 46); STRING_LITERAL(T839829468_685, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump" "f */$N/* The generated code is subject to the original license. " "*/$N", 131); STRING_LITERAL(T839829468_686, "0.15.0", 6); STRING_LITERAL(T839829468_687, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump" "f */$N/* The generated code is subject to the original license. " "*/$N/* Compiled for: $2, $3, $4 */$N/* Command for C compiler:$n" " $5 */$N", 201); extern NIM_CONST TY175082 Os_175068_4151366050; extern NIM_CONST TY175510 Cpu_175496_4151366050; STRING_LITERAL(T839829468_688, "#define NIM_INTBITS $1", 22); STRING_LITERAL(T839829468_689, "typedef struct {$1} NimThreadVars;$n", 36); STRING_LITERAL(T839829468_690, "#include \"nimbase.h\"", 20); STRING_LITERAL(T839829468_691, "#include \"$1\"$N", 15); STRING_LITERAL(T839829468_692, "#include $1$N", 13); STRING_LITERAL(T839829468_693, "extern \"C\"", 10); STRING_LITERAL(T839829468_694, "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n", 61); STRING_LITERAL(T839829468_695, "__$1__", 6); STRING_LITERAL(T839829468_696, "#ifndef $1$n#define $1$n", 24); STRING_LITERAL(T839829468_697, "N_CDECL(void, NimMain)(void);$n", 31); STRING_LITERAL(T839829468_698, "#endif /* $1 */$n", 17); Tcgen527027* generatedheader_530201_839829468; extern TNimType NTI527015; /* BModule */ Ropeobj177006* indent_530655_839829468; extern TNimType NTI177004; /* Rope */ extern Gcheap49418 gch_49458_1689653243; Ropeobj177006* nimtv_536656_839829468; Ttypeseq290836* nimtvdeps_536674_839829468; extern TNimType NTI290836; /* TTypeSeq */ Intset266030 nimtvdeclared_536675_839829468; extern TNimType NTI266030; /* IntSet */ NI breakpointid_546860_839829468; Ropeobj177006* gbreakpoints_546861_839829468; extern TY527153* gmodules_527170_3723162438; extern TNimType NTI527027; /* TCGen */ extern Debuginfo201009 gdebuginfo_201470_1926258066; extern Toption168009Set goptions_168128_2607990831; extern TNimType NTI290804; /* TSymSeq */ extern Tglobaloption168013Set gglobaloptions_168130_2607990831; extern NimStringDesc* headerfile_168138_2607990831; extern NimStringDesc* gprojectfull_168211_2607990831; extern Tcommands168076 gcmd_168132_2607990831; extern NI gerrorcounter_190069_155036129; extern Ropeobj177006* rnl_177903_2381377266; extern NI gforwardedprocscounter_527171_3723162438; extern TNimType NTI290244; /* TTypeKind */ extern TNimType NTI201017; /* seq[(string, int)] */ extern Tsystemcc271002 ccompiler_271431_2528170400; extern NimStringDesc* tnl_175644_4151366050; extern NI floatsize_175642_4151366050; extern Tgcmode168080 gselectedgc_168133_2607990831; extern TNimType NTI290020; /* TNodeKind */ extern TNimType NTI134602; /* seq[string] */ extern TNimType NTI290435; /* TSymKind */ extern TNimType NTI290816; /* TLoc */ extern NI intsize_175641_4151366050; extern TNimType NTI290524; /* TMagic */ extern TNimType NTI189350; /* seq[Rope] */ extern TNimType NTI290796; /* TNodeSeq */ extern Ropeobj177006* mainmodprocs_527148_3723162438; extern Ropeobj177006* maindatinit_527151_3723162438; extern Ropeobj177006* mainmodinit_527149_3723162438; extern Ropeobj177006* othermodsinit_527150_3723162438; extern Tsystemos175004 targetos_175629_4151366050; extern TY189612* fileinfos_189629_155036129; extern Tsystemcpu175452 targetcpu_175627_4151366050; extern Ropeobj177006* gmapping_527152_3723162438; N_NIMCALL(void, T839829468_2)(void) { nimGCvisit((void*)generatedheader_530201_839829468, 0); } N_NIMCALL(void, T839829468_3)(void) { nimGCvisit((void*)indent_530655_839829468, 0); } static N_INLINE(Cell46904*, usrtocell_51040_1689653243)(void* usr0) { Cell46904* result0; result0 = (Cell46904*)0; result0 = ((Cell46904*) ((NI)((NU64)(((NI) (usr0))) - (NU64)(((NI)sizeof(Cell46904)))))); return result0; } static N_INLINE(void, rtladdzct_52201_1689653243)(Cell46904* c0) { addzct_51017_1689653243((&gch_49458_1689653243.zct), c0); } static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0) { { Cell46904* c0; if (!!((src0 == NIM_NIL))) goto LA3; c0 = usrtocell_51040_1689653243(src0); (*c0).refcount += ((NI) 8); } LA3: ; { Cell46904* c0; if (!!(((*dest0) == NIM_NIL))) goto LA7; c0 = usrtocell_51040_1689653243((*dest0)); { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA11; rtladdzct_52201_1689653243(c0); } LA11: ; } LA7: ; (*dest0) = src0; } N_NIMCALL(void, T839829468_5)(void) { nimGCvisit((void*)nimtv_536656_839829468, 0); } N_NIMCALL(void, T839829468_6)(void) { nimGCvisit((void*)nimtvdeps_536674_839829468, 0); } static N_INLINE(void, nimGCunrefNoCycle)(void* p0) { Cell46904* c0; c0 = usrtocell_51040_1689653243(p0); { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA3; rtladdzct_52201_1689653243(c0); } LA3: ; } N_NIMCALL(void, T839829468_7)(void) { nimGCvisit((void*)nimtvdeclared_536675_839829468.head, 0); nimGCvisit((void*)nimtvdeclared_536675_839829468.data, 0); } N_NIMCALL(void, T839829468_8)(void) { nimGCvisit((void*)gbreakpoints_546861_839829468, 0); } N_NIMCALL(Tcgen527027*, getcgenmodule_530226_839829468)(Tsym290834* s0) { Tcgen527027* result0; result0 = (Tcgen527027*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (((NI) 0) <= (*s0).position); if (!(LOC3)) goto LA4; LOC3 = ((*s0).position < (gmodules_527170_3723162438 ? gmodules_527170_3723162438->Sup.len : 0)); LA4: ; if (!LOC3) goto LA5; result0 = gmodules_527170_3723162438->data[(*s0).position]; } goto LA1; LA5: ; { result0 = NIM_NIL; } LA1: ; return result0; } static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0) { void* LOC1; LOC1 = (void*)0; LOC1 = memcpy(dest0, source0, ((size_t) (size0))); } static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0) { copymem_7485_1689653243(((void*) ((&(*dest0).data[((*dest0).Sup.len)- 0]))), ((void*) ((*src0).data)), ((NI) ((NI)((*src0).Sup.len + ((NI) 1))))); (*dest0).Sup.len += (*src0).Sup.len; } N_NIMCALL(NU32, hashowner_530977_839829468)(Tsym290834* s0) { NU32 result0; Tsym290834* m0; Tsym290834* p0; result0 = (NU32)0; m0 = s0; { while (1) { if (!!(((*m0).kind == ((Tsymkind290435) 6)))) goto LA2; m0 = (*m0).owner; } LA2: ; } p0 = (*m0).owner; result0 = register_201121_1926258066((&gdebuginfo_201470_1926258066), (*(*p0).name).s, (*(*m0).name).s); return result0; } static N_INLINE(void, incref_53019_1689653243)(Cell46904* c0) { (*c0).refcount = (NI)((NU64)((*c0).refcount) + (NU64)(((NI) 8))); } static N_INLINE(void, decref_52601_1689653243)(Cell46904* c0) { { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA3; rtladdzct_52201_1689653243(c0); } LA3: ; } static N_INLINE(void, asgnRef)(void** dest0, void* src0) { { Cell46904* LOC5; if (!!((src0 == NIM_NIL))) goto LA3; LOC5 = (Cell46904*)0; LOC5 = usrtocell_51040_1689653243(src0); incref_53019_1689653243(LOC5); } LA3: ; { Cell46904* LOC10; if (!!(((*dest0) == NIM_NIL))) goto LA8; LOC10 = (Cell46904*)0; LOC10 = usrtocell_51040_1689653243((*dest0)); decref_52601_1689653243(LOC10); } LA8: ; (*dest0) = src0; } N_NIMCALL(Toption168009Set, initprocoptions_560635_839829468)(Tcgen527027* m0) { Toption168009Set result0; memset((void*)(&result0), 0, sizeof(result0)); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0)) goto LA3; result0 = (goptions_168128_2607990831 & ~ 32768); } goto LA1; LA3: ; { result0 = goptions_168128_2607990831; } LA1: ; return result0; } N_NIMCALL(Tcproc527021*, newpreinitproc_560625_839829468)(Tcgen527027* m0) { Tcproc527021* result0; result0 = (Tcproc527021*)0; result0 = newproc_527206_3723162438(NIM_NIL, m0); (*result0).labels = ((NI) 100000); return result0; } N_NIMCALL(Tcproc527021*, newpostinitproc_560630_839829468)(Tcgen527027* m0) { Tcproc527021* result0; result0 = (Tcproc527021*)0; result0 = newproc_527206_3723162438(NIM_NIL, m0); (*result0).labels = ((NI) 200000); return result0; } N_NIMCALL(Ropeobj177006*, gettempname_531598_839829468)(Tcgen527027* m0) { Ropeobj177006* result0; Ropeobj177006* LOC1; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = rope_177401_2381377266(((NI64) ((*m0).labels))); result0 = HEX26_177418_2381377266((*m0).tmpbase, LOC1); (*m0).labels += ((NI) 1); return result0; } N_NIMCALL(Tcgen527027*, rawnewmodule_560663_839829468)(Tsym290834* module0, NimStringDesc* filename0) { Tcgen527027* result0; NimStringDesc* LOC1; NU32 LOC2; NimStringDesc* LOC3; NimStringDesc* LOC4; NimStringDesc* LOC5; result0 = (Tcgen527027*)0; result0 = (Tcgen527027*) newObj((&NTI527015), sizeof(Tcgen527027)); (*result0).Sup.Sup.m_type = (&NTI527027); LOC1 = (NimStringDesc*)0; LOC2 = (NU32)0; LOC2 = hashowner_530977_839829468(module0); LOC3 = (NimStringDesc*)0; LOC3 = HEX24_8401_1689653243(((NU64) (LOC2))); LOC1 = rawNewString(LOC3->Sup.len + 2); appendString(LOC1, ((NimStringDesc*) &T839829468_11)); appendString(LOC1, LOC3); appendString(LOC1, ((NimStringDesc*) &T839829468_12)); asgnRefNoCycle((void**) (&(*result0).tmpbase), rope_177277_2381377266(LOC1)); initlinkedlist_147031_3771138726((&(*result0).headerfiles)); initintset_266885_2627731572((&(*result0).declaredthings)); initintset_266885_2627731572((&(*result0).declaredprotos)); LOC4 = (NimStringDesc*)0; LOC4 = (*result0).cfilename; (*result0).cfilename = copyStringRC1(filename0); if (LOC4) nimGCunrefNoCycle(LOC4); LOC5 = (NimStringDesc*)0; LOC5 = (*result0).filename; (*result0).filename = copyStringRC1(filename0); if (LOC5) nimGCunrefNoCycle(LOC5); initidtable_294019_850551059((&(*result0).typecache)); initidtable_294019_850551059((&(*result0).forwtypecache)); asgnRefNoCycle((void**) (&(*result0).module), module0); initintset_266885_2627731572((&(*result0).typeinfomarker)); asgnRef((void**) (&(*result0).initproc), newproc_527206_3723162438(NIM_NIL, result0)); (*(*result0).initproc).options = initprocoptions_560635_839829468(result0); asgnRef((void**) (&(*result0).preinitproc), newpreinitproc_560625_839829468(result0)); asgnRef((void**) (&(*result0).postinitproc), newpostinitproc_560630_839829468(result0)); initnodetable_294085_850551059((&(*result0).datacache)); if ((*result0).typestack) nimGCunrefNoCycle((*result0).typestack); (*result0).typestack = (Ttypeseq290836*) newSeqRC1((&NTI290836), 0); if ((*result0).forwardedprocs) nimGCunrefNoCycle((*result0).forwardedprocs); (*result0).forwardedprocs = (Tsymseq290804*) newSeqRC1((&NTI290804), 0); asgnRefNoCycle((void**) (&(*result0).typenodesname), gettempname_531598_839829468(result0)); asgnRefNoCycle((void**) (&(*result0).nimtypesname), gettempname_531598_839829468(result0)); { if (!(((*module0).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0)) goto LA8; (*result0).flags |= ((NU8)1)<<((((Codegenflag527025) 0))%(sizeof(NU8)*8)); (*(*result0).preinitproc).options &= ~(((NU32)1) << ((((Toption168009) 15)) % (sizeof(NU32)*8))); (*(*result0).postinitproc).options &= ~(((NU32)1) << ((((Toption168009) 15)) % (sizeof(NU32)*8))); } LA8: ; return result0; } N_NIMCALL(Tcgen527027*, rawnewmodule_561038_839829468)(Tsym290834* module0) { Tcgen527027* result0; NimStringDesc* LOC1; result0 = (Tcgen527027*)0; LOC1 = (NimStringDesc*)0; LOC1 = tofullpath_190261_155036129(((NI32) ((*module0).position))); result0 = rawnewmodule_560663_839829468(module0, LOC1); return result0; } N_NIMCALL(Tcgen527027*, newmodule_561044_839829468)(Tsym290834* module0) { Tcgen527027* result0; result0 = (Tcgen527027*)0; { Tcgen527027* LOC3; NimStringDesc* LOC6; LOC3 = (Tcgen527027*)0; LOC3 = getcgenmodule_530226_839829468(module0); if (!!((LOC3 == NIM_NIL))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_194185_1689653243(T839829468_9); internalerror_194113_155036129(LOC6); } LA4: ; result0 = rawnewmodule_561038_839829468(module0); { if (!((gmodules_527170_3723162438 ? gmodules_527170_3723162438->Sup.len : 0) <= (*module0).position)) goto LA9; gmodules_527170_3723162438 = (TY527153*) setLengthSeq(&(gmodules_527170_3723162438)->Sup, sizeof(Tcgen527027*), ((NI) ((NI)((*module0).position + ((NI) 1))))); } LA9: ; asgnRef((void**) (&gmodules_527170_3723162438->data[(*module0).position]), result0); { if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 2))&63U)))!=0)) goto LA13; { NimStringDesc* LOC19; NimStringDesc* LOC20; if (!(((*module0).flags &(1U<<((NU)(((Tsymflag290184) 25))&31U)))!=0)) goto LA17; LOC19 = (NimStringDesc*)0; LOC20 = (NimStringDesc*)0; LOC20 = tofilename_190257_155036129(((NI32) ((*module0).position))); LOC19 = rawNewString(LOC20->Sup.len + 28); appendString(LOC19, ((NimStringDesc*) &T839829468_13)); appendString(LOC19, LOC20); internalerror_194113_155036129(LOC19); } LA17: ; } LA13: ; return result0; } N_NIMCALL(Tpasscontext339002*, myopen_561112_839829468)(Tsym290834* module0) { Tpasscontext339002* result0; Tcgen527027* LOC1; result0 = (Tpasscontext339002*)0; LOC1 = (Tcgen527027*)0; LOC1 = newmodule_561044_839829468(module0); result0 = &LOC1->Sup; { NIM_BOOL LOC4; NimStringDesc* f0; NimStringDesc* LOC13; NimStringDesc* LOC14; LOC4 = (NIM_BOOL)0; LOC4 = ((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 27))&63U)))!=0); if (!(LOC4)) goto LA5; LOC4 = (generatedheader_530201_839829468 == NIM_NIL); LA5: ; if (!LOC4) goto LA6; { if (!(((NI) 0) < (headerfile_168138_2607990831 ? headerfile_168138_2607990831->Sup.len : 0))) goto LA10; f0 = headerfile_168138_2607990831; } goto LA8; LA10: ; { f0 = gprojectfull_168211_2607990831; } LA8: ; LOC13 = (NimStringDesc*)0; LOC13 = completecfilepath_271854_2528170400(f0, NIM_TRUE); LOC14 = (NimStringDesc*)0; LOC14 = noschangeFileExt(LOC13, ((NimStringDesc*) &T839829468_14)); asgnRef((void**) (&generatedheader_530201_839829468), rawnewmodule_560663_839829468(module0, LOC14)); (*generatedheader_530201_839829468).flags |= ((NU8)1)<<((((Codegenflag527025) 3))%(sizeof(NU8)*8)); } LA6: ; return result0; } N_NIMCALL(NimStringDesc*, getcfile_561201_839829468)(Tcgen527027* m0) { NimStringDesc* result0; NimStringDesc* ext0; NimStringDesc* LOC13; NimStringDesc* LOC14; result0 = (NimStringDesc*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; ext0 = copyString(((NimStringDesc*) &T839829468_15)); } goto LA1; LA5: ; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = (gcmd_168132_2607990831 == ((Tcommands168076) 3)); if (LOC8) goto LA9; LOC8 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 28))&31U)))!=0); LA9: ; if (!LOC8) goto LA10; ext0 = copyString(((NimStringDesc*) &T839829468_16)); } goto LA1; LA10: ; { ext0 = copyString(((NimStringDesc*) &T839829468_17)); } LA1: ; LOC13 = (NimStringDesc*)0; LOC13 = withpackagename_169065_2607990831((*m0).cfilename); LOC14 = (NimStringDesc*)0; LOC14 = completecfilepath_271854_2528170400(LOC13, NIM_TRUE); result0 = noschangeFileExt(LOC14, ext0); return result0; } N_NIMCALL(Tpasscontext339002*, myopencached_561246_839829468)(Tsym290834* module0, Trodreader330021* rd0) { Tpasscontext339002* result0; Tcgen527027* m0; NimStringDesc* LOC1; result0 = (Tpasscontext339002*)0; m0 = newmodule_561044_839829468(module0); LOC1 = (NimStringDesc*)0; LOC1 = getcfile_561201_839829468(m0); readmergeinfo_528613_2760143328(LOC1, m0); result0 = &m0->Sup; return result0; } static N_INLINE(NIM_BOOL, skipcodegen_339085_2355241294)(Tnode290802* n0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = (((NI) 0) < gerrorcounter_190069_155036129); return result0; } N_NIMCALL(void, fillloc_530282_839829468)(Tloc290816* a0, Tlockind290808 k0, Ttype290840* typ0, Ropeobj177006* r0, Tstorageloc290812 s0) { { if (!((*a0).k == ((Tlockind290808) 0))) goto LA3; (*a0).k = k0; unsureAsgnRef((void**) (&(*a0).t), typ0); (*a0).s = s0; { if (!((*a0).r == NIM_NIL)) goto LA7; unsureAsgnRef((void**) (&(*a0).r), r0); } LA7: ; } LA3: ; } N_NIMCALL(NIM_BOOL, iskeyword_530960_839829468)(Tident197010* w0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; switch ((*w0).Sup.id) { case ((NI) 200) ... ((NI) 262): case ((NI) 4) ... ((NI) 70): case ((NI) 138): { result0 = NIM_TRUE; goto BeforeRet; } break; default: { result0 = NIM_FALSE; goto BeforeRet; } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj177006*, manglename_531205_839829468)(Tsym290834* s0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = (*s0).loc.r; { NIM_BOOL keeporigname0; NIM_BOOL LOC5; NIM_BOOL LOC6; NIM_BOOL LOC9; NimStringDesc* LOC10; if (!(result0 == NIM_NIL)) goto LA3; LOC5 = (NIM_BOOL)0; LOC6 = (NIM_BOOL)0; LOC6 = ((2824 &(1U<<((NU)((*s0).kind)&31U)))!=0); if (!(LOC6)) goto LA7; LOC6 = ((IL64(2149580812) & (*s0).flags) == 0); LA7: ; LOC5 = LOC6; if (!(LOC5)) goto LA8; LOC9 = (NIM_BOOL)0; LOC9 = iskeyword_530960_839829468((*s0).name); LOC5 = !(LOC9); LA8: ; keeporigname0 = LOC5; LOC10 = (NimStringDesc*)0; LOC10 = mangle_526847_2036603609((*(*s0).name).s); result0 = rope_177277_2381377266(LOC10); { if (!keeporigname0) goto LA13; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_18)); } goto LA11; LA13: ; { TY531289 LOC16; Ropeobj177006* LOC17; Ropeobj177006* LOC18; TY531289 LOC19; Ropeobj177006* LOC20; NU32 LOC21; Ropeobj177006* LOC22; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (Ropeobj177006*)0; LOC17 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_12), LOC16, 0); add_177482_2381377266(&result0, LOC17); LOC18 = (Ropeobj177006*)0; LOC18 = rope_177401_2381377266(((NI64) ((*s0).Sup.id))); add_177482_2381377266(&result0, LOC18); memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (Ropeobj177006*)0; LOC20 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_12), LOC19, 0); add_177482_2381377266(&result0, LOC20); LOC21 = (NU32)0; LOC21 = hashowner_530977_839829468(s0); LOC22 = (Ropeobj177006*)0; LOC22 = rope_177401_2381377266(((NI64) (LOC21))); add_177482_2381377266(&result0, LOC22); } LA11: ; asgnRefNoCycle((void**) (&(*s0).loc.r), result0); } LA3: ; return result0; } N_NIMCALL(void, fillprocloc_537201_839829468)(Tsym290834* sym0) { { Ropeobj177006* LOC5; if (!((*sym0).loc.k == ((Tlockind290808) 0))) goto LA3; LOC5 = (Ropeobj177006*)0; LOC5 = manglename_531205_839829468(sym0); fillloc_530282_839829468((&(*sym0).loc), ((Tlockind290808) 7), (*sym0).typ, LOC5, ((Tstorageloc290812) 2)); } LA3: ; } N_NIMCALL(void, useheader_530369_839829468)(Tcgen527027* m0, Tsym290834* sym0) { { NimStringDesc* LOC5; NIM_BOOL LOC6; if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 6))&15U)))!=0)) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = getstr_295230_850551059((*(*sym0).annex).path); LOC6 = (NIM_BOOL)0; LOC6 = includestr_147249_3771138726((&(*m0).headerfiles), LOC5); } LA3: ; } static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0) { (*dest0).data[((*dest0).Sup.len)- 0] = c0; (*dest0).data[((NI)((*dest0).Sup.len + ((NI) 1)))- 0] = 0; (*dest0).Sup.len += ((NI) 1); } N_NIMCALL(NIM_BOOL, isactivated_559431_839829468)(Tsym290834* prc0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = !(((*prc0).typ == NIM_NIL)); return result0; } N_NIMCALL(void, addforwardedproc_530203_839829468)(Tcgen527027* m0, Tsym290834* prc0) { (*m0).forwardedprocs = (Tsymseq290804*) incrSeqV2(&((*m0).forwardedprocs)->Sup, sizeof(Tsym290834*)); asgnRefNoCycle((void**) (&(*m0).forwardedprocs->data[(*m0).forwardedprocs->Sup.len]), prc0); ++(*m0).forwardedprocs->Sup.len; gforwardedprocscounter_527171_3723162438 += ((NI) 1); } N_NIMCALL(void, genclinedir_530725_839829468)(Ropeobj177006** r0, NimStringDesc* filename0, NI line0) { { TY530811 LOC5; NimStringDesc* LOC6; if (!((goptions_168128_2607990831 &(1U<<((NU)(((Toption168009) 10))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (NimStringDesc*)0; LOC6 = makesinglelinecstring_526835_2036603609(filename0); LOC5[0] = rope_177277_2381377266(LOC6); LOC5[1] = rope_177401_2381377266(((NI64) (line0))); addf_178205_2381377266(r0, ((NimStringDesc*) &T839829468_21), LOC5, 2); } LA3: ; } static N_INLINE(NI, tolinenumber_190415_155036129)(Tlineinfo189336 info0) { NI result0; result0 = (NI)0; result0 = ((NI) (info0.line)); return result0; } N_NIMCALL(NI, safelinenm_530721_839829468)(Tlineinfo189336 info0) { NI result0; result0 = (NI)0; result0 = tolinenumber_190415_155036129(info0); { if (!(result0 < ((NI) 0))) goto LA3; result0 = ((NI) 0); } LA3: ; return result0; } N_NIMCALL(void, genclinedir_530813_839829468)(Ropeobj177006** r0, Tlineinfo189336 info0) { NimStringDesc* LOC1; NI LOC2; LOC1 = (NimStringDesc*)0; LOC1 = tofullpath_190261_155036129(info0.fileindex); LOC2 = (NI)0; LOC2 = safelinenm_530721_839829468(info0); genclinedir_530725_839829468(r0, LOC1, LOC2); } N_NIMCALL(Tctypekind527007, mapsettype_531389_839829468)(Ttype290840* typ0) { Tctypekind527007 result0; NI64 LOC1; result0 = (Tctypekind527007)0; LOC1 = (NI64)0; LOC1 = getsize_318135_3876443242(typ0); switch (((NI) (LOC1))) { case ((NI) 1): { result0 = ((Tctypekind527007) 4); } break; case ((NI) 2): { result0 = ((Tctypekind527007) 5); } break; case ((NI) 4): { result0 = ((Tctypekind527007) 6); } break; case ((NI) 8): { result0 = ((Tctypekind527007) 7); } break; default: { result0 = ((Tctypekind527007) 17); } break; } return result0; } N_NIMCALL(Tctypekind527007, maptype_531394_839829468)(Ttype290840* typ0) { Tctypekind527007 result0; result0 = (Tctypekind527007)0; switch ((*typ0).kind) { case ((Ttypekind290244) 0): case ((Ttypekind290244) 7): { result0 = ((Tctypekind527007) 0); } break; case ((Ttypekind290244) 1): { result0 = ((Tctypekind527007) 2); } break; case ((Ttypekind290244) 2): { result0 = ((Tctypekind527007) 1); } break; case ((Ttypekind290244) 19): { result0 = mapsettype_531389_839829468(typ0); } break; case ((Ttypekind290244) 27): case ((Ttypekind290244) 4): case ((Ttypekind290244) 16): case ((Ttypekind290244) 48): { result0 = ((Tctypekind527007) 17); } break; case ((Ttypekind290244) 17): case ((Ttypekind290244) 18): { result0 = ((Tctypekind527007) 19); } break; case ((Ttypekind290244) 10): case ((Ttypekind290244) 11): case ((Ttypekind290244) 12): case ((Ttypekind290244) 13): case ((Ttypekind290244) 15): case ((Ttypekind290244) 46): case ((Ttypekind290244) 47): case ((Ttypekind290244) 49): case ((Ttypekind290244) 8): { Ttype290840* LOC8; LOC8 = (Ttype290840*)0; LOC8 = lastson_293377_850551059(typ0); result0 = maptype_531394_839829468(LOC8); } break; case ((Ttypekind290244) 14): { { NI64 LOC12; LOC12 = (NI64)0; LOC12 = firstord_318001_3876443242(typ0); if (!(LOC12 < IL64(0))) goto LA13; result0 = ((Tctypekind527007) 6); } goto LA10; LA13: ; { NI64 LOC16; LOC16 = (NI64)0; LOC16 = getsize_318135_3876443242(typ0); switch (((NI) (LOC16))) { case ((NI) 1): { result0 = ((Tctypekind527007) 13); } break; case ((NI) 2): { result0 = ((Tctypekind527007) 14); } break; case ((NI) 4): { result0 = ((Tctypekind527007) 6); } break; case ((NI) 8): { result0 = ((Tctypekind527007) 7); } break; default: { internalerror_194113_155036129(((NimStringDesc*) &T839829468_25)); } break; } } LA10: ; } break; case ((Ttypekind290244) 20): { result0 = maptype_531394_839829468((*typ0).sons->data[((NI) 0)]); } break; case ((Ttypekind290244) 21): case ((Ttypekind290244) 23): case ((Ttypekind290244) 22): { Ttype290840* base0; Ttype290840* LOC24; LOC24 = (Ttype290840*)0; LOC24 = lastson_293377_850551059(typ0); base0 = skiptypes_294099_850551059(LOC24, IL64(211106232576256)); switch ((*base0).kind) { case ((Ttypekind290244) 27): case ((Ttypekind290244) 4): case ((Ttypekind290244) 16): case ((Ttypekind290244) 48): { result0 = ((Tctypekind527007) 18); } break; default: { result0 = ((Tctypekind527007) 20); } break; } } break; case ((Ttypekind290244) 26): { result0 = ((Tctypekind527007) 20); } break; case ((Ttypekind290244) 24): { result0 = ((Tctypekind527007) 22); } break; case ((Ttypekind290244) 25): { { if (!!(((*typ0).callconv == ((Tcallingconvention290002) 8)))) goto LA32; result0 = ((Tctypekind527007) 23); } goto LA30; LA32: ; { result0 = ((Tctypekind527007) 19); } LA30: ; } break; case ((Ttypekind290244) 28): { result0 = ((Tctypekind527007) 21); } break; case ((Ttypekind290244) 29): { result0 = ((Tctypekind527007) 24); } break; case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44): { result0 = ((Tctypekind527007) ((NI)(((NI) ((NI)(((NI) ((*typ0).kind)) - ((NI) 31)))) + ((NI) 3)))); } break; case ((Ttypekind290244) 59): { { Ttype290840* LOC43; if (!!(((*typ0).n == NIM_NIL))) goto LA41; LOC43 = (Ttype290840*)0; LOC43 = lastson_293377_850551059(typ0); result0 = maptype_531394_839829468(LOC43); } goto LA39; LA41: ; { internalerror_194113_155036129(((NimStringDesc*) &T839829468_25)); } LA39: ; } break; default: { internalerror_194113_155036129(((NimStringDesc*) &T839829468_25)); } break; } return result0; } N_NIMCALL(NIM_BOOL, isimportedcpptype_531478_839829468)(Ttype290840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = !(((*t0).sym == NIM_NIL)); if (!(LOC1)) goto LA2; LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NIM_BOOL, needscomplexassignment_531511_839829468)(Ttype290840* typ0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = containsgarbagecollectedref_318117_3876443242(typ0); return result0; } static N_INLINE(NIM_BOOL, isobjlackingtypefield_531515_839829468)(Ttype290840* typ0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC3; NIM_BOOL LOC4; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((*typ0).kind == ((Ttypekind290244) 17)); if (!(LOC1)) goto LA2; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0); if (!(LOC4)) goto LA5; LOC4 = ((*typ0).sons->data[((NI) 0)] == NIM_NIL); LA5: ; LOC3 = LOC4; if (LOC3) goto LA6; LOC3 = ispureobject_318138_3876443242(typ0); LA6: ; LOC1 = LOC3; LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NIM_BOOL, isinvalidreturntype_531550_839829468)(Ttype290840* rettype0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!(rettype0 == NIM_NIL)) goto LA3; result0 = NIM_TRUE; } goto LA1; LA3: ; { Tctypekind527007 LOC6; LOC6 = (Tctypekind527007)0; LOC6 = maptype_531394_839829468(rettype0); switch (LOC6) { case ((Tctypekind527007) 17): { Ttype290840* LOC8; LOC8 = (Ttype290840*)0; LOC8 = skiptypes_294099_850551059(rettype0, IL64(211106232576256)); result0 = !(((14680064 &((NU64)1<<((NU)((*LOC8).kind)&63U)))!=0)); } break; case ((Tctypekind527007) 19): { Ttype290840* t0; NIM_BOOL LOC16; NIM_BOOL LOC18; NIM_BOOL LOC20; t0 = skiptypes_294099_850551059(rettype0, IL64(211106232576256)); { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = isimportedcpptype_531478_839829468(rettype0); if (LOC12) goto LA13; LOC12 = isimportedcpptype_531478_839829468(t0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; goto BeforeRet; } LA14: ; LOC16 = (NIM_BOOL)0; LOC16 = needscomplexassignment_531511_839829468(t0); if (LOC16) goto LA17; LOC18 = (NIM_BOOL)0; LOC18 = ((*t0).kind == ((Ttypekind290244) 17)); if (!(LOC18)) goto LA19; LOC20 = (NIM_BOOL)0; LOC20 = isobjlackingtypefield_531515_839829468(t0); LOC18 = !(LOC20); LA19: ; LOC16 = LOC18; LA17: ; result0 = LOC16; } break; default: { result0 = NIM_FALSE; } break; } } LA1: ; }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj177006*, typename_531292_839829468)(Ttype290840* typ0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NimStringDesc* LOC5; if (!!(((*typ0).sym == NIM_NIL))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = mangle_526847_2036603609((*(*(*typ0).sym).name).s); result0 = rope_177277_2381377266(LOC5); } goto LA1; LA3: ; { TY531289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_28), LOC7, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, gettypename_531313_839829468)(Ttype290840* typ0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*typ0).sym == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = !(((96 & (*(*typ0).sym).flags) == 0)); LA4: ; if (!LOC3) goto LA5; result0 = (*(*typ0).sym).loc.r; } goto LA1; LA5: ; { { Ropeobj177006* LOC12; Ropeobj177006* LOC13; if (!((*typ0).loc.r == NIM_NIL)) goto LA10; LOC12 = (Ropeobj177006*)0; LOC12 = typename_531292_839829468(typ0); LOC13 = (Ropeobj177006*)0; LOC13 = rope_177401_2381377266(((NI64) ((*typ0).Sup.id))); asgnRefNoCycle((void**) (&(*typ0).loc.r), HEX26_177418_2381377266(LOC12, LOC13)); } LA10: ; result0 = (*typ0).loc.r; } LA1: ; { NimStringDesc* LOC18; if (!(result0 == NIM_NIL)) goto LA16; LOC18 = (NimStringDesc*)0; LOC18 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI290244))->Sup.len + 13); appendString(LOC18, ((NimStringDesc*) &T839829468_29)); appendString(LOC18, reprEnum((NI)(*typ0).kind, (&NTI290244))); internalerror_194113_155036129(LOC18); } LA16: ; return result0; } N_NIMCALL(Ropeobj177006*, typenameorliteral_531898_839829468)(Ttype290840* t0, NimStringDesc* literal0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = !(((*t0).sym == NIM_NIL)); if (!(LOC4)) goto LA5; LOC4 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0); LA5: ; LOC3 = LOC4; if (!(LOC3)) goto LA6; LOC3 = ((*(*t0).sym).magic == ((Tmagic290524) 0)); LA6: ; if (!LOC3) goto LA7; result0 = gettypename_531313_839829468(t0); } goto LA1; LA7: ; { result0 = rope_177277_2381377266(literal0); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, getsimpletypedesc_531936_839829468)(Tcgen527027* m0, Ttype290840* typ0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; switch ((*typ0).kind) { case ((Ttypekind290244) 26): { result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_30)); } break; case ((Ttypekind290244) 28): { Ropeobj177006* LOC3; LOC3 = (Ropeobj177006*)0; LOC3 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_31)); result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_32)); } break; case ((Ttypekind290244) 29): { result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_33)); } break; case ((Ttypekind290244) 1): { result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_34)); } break; case ((Ttypekind290244) 2): { result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_35)); } break; case ((Ttypekind290244) 5): { result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_18)); } break; case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44): { result0 = typenameorliteral_531898_839829468(typ0, Numericaltypetostr_531941_839829468[((*typ0).kind)- 31]); } break; case ((Ttypekind290244) 13): case ((Ttypekind290244) 20): case ((Ttypekind290244) 15): { result0 = getsimpletypedesc_531936_839829468(m0, (*typ0).sons->data[((NI) 0)]); } break; case ((Ttypekind290244) 59): { { Ttype290840* LOC15; if (!!(((*typ0).n == NIM_NIL))) goto LA13; LOC15 = (Ttype290840*)0; LOC15 = lastson_293377_850551059(typ0); result0 = getsimpletypedesc_531936_839829468(m0, LOC15); } goto LA11; LA13: ; { internalerror_194113_155036129(((NimStringDesc*) &T839829468_50)); } LA11: ; } break; case ((Ttypekind290244) 11): { Ttype290840* LOC18; LOC18 = (Ttype290840*)0; LOC18 = lastson_293377_850551059(typ0); result0 = getsimpletypedesc_531936_839829468(m0, LOC18); } break; default: { result0 = NIM_NIL; } break; } return result0; } N_NIMCALL(Ropeobj177006*, cachegettype_531593_839829468)(Tidtable290850 tab0, Ttype290840* key0) { Ropeobj177006* result0; Tidobj197004* LOC1; TNimObject* LOC2; result0 = (Ropeobj177006*)0; LOC1 = (Tidobj197004*)0; LOC1 = &key0->Sup; LOC2 = (TNimObject*)0; LOC2 = idtableget_297086_2984716966(tab0, LOC1); result0 = ((Ropeobj177006*) (LOC2)); return result0; } N_NIMCALL(Ropeobj177006*, gettypepre_531972_839829468)(Tcgen527027* m0, Ttype290840* typ0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { if (!(typ0 == NIM_NIL)) goto LA3; result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_26)); } goto LA1; LA3: ; { result0 = getsimpletypedesc_531936_839829468(m0, typ0); { if (!(result0 == NIM_NIL)) goto LA8; result0 = cachegettype_531593_839829468((*m0).typecache, typ0); } LA8: ; } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, isimportedtype_531451_839829468)(Ttype290840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = !(((*t0).sym == NIM_NIL)); if (!(LOC1)) goto LA2; LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NimStringDesc*, getforwardstructformat_532015_839829468)(Tcgen527027* m0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; result0 = copyString(((NimStringDesc*) &T839829468_54)); } goto LA1; LA5: ; { result0 = copyString(((NimStringDesc*) &T839829468_55)); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, structorunion_532001_839829468)(Ttype290840* t0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag290431) 1))&31U)))!=0)) goto LA3; result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_56)); } goto LA1; LA3: ; { result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_57)); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, gettypeforward_532039_839829468)(Tcgen527027* m0, Ttype290840* typ0) { Ropeobj177006* result0; { result0 = (Ropeobj177006*)0; result0 = cachegettype_531593_839829468((*m0).forwtypecache, typ0); { if (!!((result0 == NIM_NIL))) goto LA3; goto BeforeRet; } LA3: ; result0 = gettypepre_531972_839829468(m0, typ0); { if (!!((result0 == NIM_NIL))) goto LA7; goto BeforeRet; } LA7: ; switch ((*typ0).kind) { case ((Ttypekind290244) 24): case ((Ttypekind290244) 18): case ((Ttypekind290244) 17): { Tidobj197004* LOC17; TNimObject* LOC18; result0 = gettypename_531313_839829468(typ0); { NIM_BOOL LOC12; NimStringDesc* LOC15; TY530811 LOC16; LOC12 = (NIM_BOOL)0; LOC12 = isimportedtype_531451_839829468(typ0); if (!!(LOC12)) goto LA13; LOC15 = (NimStringDesc*)0; LOC15 = getforwardstructformat_532015_839829468(m0); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = structorunion_532001_839829468(typ0); LOC16[1] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 2))- 0], LOC15, LOC16, 2); } LA13: ; LOC17 = (Tidobj197004*)0; LOC17 = &typ0->Sup; LOC18 = (TNimObject*)0; LOC18 = &result0->Sup; idtableput_297094_2984716966((&(*m0).forwtypecache), LOC17, LOC18); } break; default: { NimStringDesc* LOC20; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI290244))->Sup.len + 16); appendString(LOC20, ((NimStringDesc*) &T839829468_58)); appendString(LOC20, reprEnum((NI)(*typ0).kind, (&NTI290244))); appendChar(LOC20, 41); internalerror_194113_155036129(LOC20); } break; } }BeforeRet: ; return result0; } N_NIMCALL(void, pushtype_531958_839829468)(Tcgen527027* m0, Ttype290840* typ0) { (*m0).typestack = (Ttypeseq290836*) incrSeqV2(&((*m0).typestack)->Sup, sizeof(Ttype290840*)); asgnRefNoCycle((void**) (&(*m0).typestack->data[(*m0).typestack->Sup.len]), typ0); ++(*m0).typestack->Sup.len; } N_NIMCALL(Ropeobj177006*, gettypedescweak_532079_839829468)(Tcgen527027* m0, Ttype290840* t0, Intset266030* check0) { Ropeobj177006* result0; Ttype290840* etb0; result0 = (Ropeobj177006*)0; etb0 = skiptypes_294099_850551059(t0, IL64(211106232576256)); switch ((*etb0).kind) { case ((Ttypekind290244) 17): case ((Ttypekind290244) 18): { { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = isimportedcpptype_531478_839829468(etb0); if (!(LOC4)) goto LA5; LOC4 = ((*t0).kind == ((Ttypekind290244) 11)); LA5: ; if (!LOC4) goto LA6; result0 = gettypedescaux_531505_839829468(m0, t0, check0); } goto LA2; LA6: ; { Ttype290840* x0; x0 = getuniquetype_526640_2036603609(etb0); result0 = gettypeforward_532039_839829468(m0, x0); pushtype_531958_839829468(m0, x0); } LA2: ; } break; case ((Ttypekind290244) 24): { Ttype290840* x0; Ropeobj177006* LOC10; x0 = getuniquetype_526640_2036603609(etb0); LOC10 = (Ropeobj177006*)0; LOC10 = gettypeforward_532039_839829468(m0, x0); result0 = HEX26_177447_2381377266(LOC10, ((NimStringDesc*) &T839829468_53)); pushtype_531958_839829468(m0, x0); } break; default: { result0 = gettypedescaux_531505_839829468(m0, t0, check0); } break; } return result0; } static N_INLINE(NI, len_291081_850551059)(Tnode290802* n0) { NI result0; result0 = (NI)0; { if (!(*n0).kindU.S6.sons == 0) goto LA3; result0 = ((NI) 0); } goto LA1; LA3: ; { result0 = ((*n0).kindU.S6.sons ? (*n0).kindU.S6.sons->Sup.len : 0); } LA1: ; return result0; } N_NIMCALL(void, appcg_530632_839829468)(Tcgen527027* m0, Ropeobj177006** c0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006* LOC1; LOC1 = (Ropeobj177006*)0; LOC1 = ropecg_530407_839829468(m0, frmt0, args0, args0Len0); add_177482_2381377266(c0, LOC1); } N_NIMCALL(NIM_BOOL, scancppgenericslot_532827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0) { NIM_BOOL result0; NI begin0; { result0 = (NIM_BOOL)0; (*cursor0) += ((NI) 1); begin0 = (*cursor0); { while (1) { if (!((NU8)(pat0->data[(*cursor0)]) == (NU8)(42))) goto LA2; (*cursor0) += ((NI) 1); } LA2: ; } { if (!(((NU8)(pat0->data[(*cursor0)])) >= ((NU8)(48)) && ((NU8)(pat0->data[(*cursor0)])) <= ((NU8)(57)))) goto LA5; (*outidx0) = ((NI) ((NI)(((NI) (((NU8)(pat0->data[(*cursor0)])))) - ((NI) 48)))); (*outstars0) = (NI)((*cursor0) - begin0); (*cursor0) += ((NI) 1); result0 = NIM_TRUE; goto BeforeRet; } goto LA3; LA5: ; { result0 = NIM_FALSE; goto BeforeRet; } LA3: ; }BeforeRet: ; return result0; } N_NIMCALL(Ttype290840*, resolvestarsincpptype_532891_839829468)(Ttype290840* typ0, NI idx0, NI stars0) { Ttype290840* result0; result0 = (Ttype290840*)0; { NI LOC3; LOC3 = (NI)0; LOC3 = len_293339_850551059(typ0); if (!(LOC3 <= idx0)) goto LA4; internalerror_194113_155036129(((NimStringDesc*) &T839829468_81)); } LA4: ; result0 = (*typ0).sons->data[idx0]; { NI i_532906_839829468; NI res_532931_839829468; i_532906_839829468 = (NI)0; res_532931_839829468 = ((NI) 1); { while (1) { if (!(res_532931_839829468 <= stars0)) goto LA8; i_532906_839829468 = res_532931_839829468; { NIM_BOOL LOC11; NI LOC13; LOC11 = (NIM_BOOL)0; LOC11 = !((result0 == NIM_NIL)); if (!(LOC11)) goto LA12; LOC13 = (NI)0; LOC13 = len_293339_850551059(result0); LOC11 = (((NI) 0) < LOC13); LA12: ; if (!LOC11) goto LA14; { if (!((*result0).kind == ((Ttypekind290244) 11))) goto LA18; result0 = (*result0).sons->data[((NI) 1)]; } goto LA16; LA18: ; { result0 = elemtype_318394_3876443242(result0); } LA16: ; } LA14: ; res_532931_839829468 += ((NI) 1); } LA8: ; } } return result0; } N_NIMCALL(NimStringDesc*, manglefield_530973_839829468)(Tident197010* name0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; result0 = mangle_526847_2036603609((*name0).s); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = iskeyword_530960_839829468(name0); if (!LOC3) goto LA4; result0->data[((NI) 0)] = nsuToUpperAsciiChar(result0->data[((NI) 0)]); } LA4: ; return result0; } N_NIMCALL(Ropeobj177006*, manglerecfieldname_532361_839829468)(Tsym290834* field0, Ttype290840* rectype0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*rectype0).sym == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = !(((96 & (*(*rectype0).sym).flags) == 0)); LA4: ; if (!LOC3) goto LA5; result0 = (*field0).loc.r; } goto LA1; LA5: ; { NimStringDesc* LOC8; LOC8 = (NimStringDesc*)0; LOC8 = manglefield_530973_839829468((*field0).name); result0 = rope_177277_2381377266(LOC8); } LA1: ; { if (!(result0 == NIM_NIL)) goto LA11; internalerror_194100_155036129((*field0).info, ((NimStringDesc*) &T839829468_96)); } LA11: ; return result0; } N_NIMCALL(Ropeobj177006*, genrecordfieldsaux_532421_839829468)(Tcgen527027* m0, Tnode290802* n0, Ropeobj177006* accessexpr0, Ttype290840* rectype0, Intset266030* check0) { Ropeobj177006* result0; Ropeobj177006* ae0; Ropeobj177006* uname0; Ropeobj177006* sname0; Ropeobj177006* a0; Tnode290802* k0; Tsym290834* field0; { result0 = (Ropeobj177006*)0; ae0 = (Ropeobj177006*)0; uname0 = (Ropeobj177006*)0; sname0 = (Ropeobj177006*)0; a0 = (Ropeobj177006*)0; k0 = (Tnode290802*)0; field0 = (Tsym290834*)0; result0 = NIM_NIL; switch ((*n0).kind) { case ((Tnodekind290020) 138): { { NI i_532447_839829468; NI HEX3Atmp_532620_839829468; NI LOC3; NI res_532623_839829468; i_532447_839829468 = (NI)0; HEX3Atmp_532620_839829468 = (NI)0; LOC3 = (NI)0; LOC3 = sonslen_293351_850551059(n0); HEX3Atmp_532620_839829468 = (NI)(LOC3 - ((NI) 1)); res_532623_839829468 = ((NI) 0); { while (1) { Ropeobj177006* LOC6; if (!(res_532623_839829468 <= HEX3Atmp_532620_839829468)) goto LA5; i_532447_839829468 = res_532623_839829468; LOC6 = (Ropeobj177006*)0; LOC6 = genrecordfieldsaux_532421_839829468(m0, (*n0).kindU.S6.sons->data[i_532447_839829468], accessexpr0, rectype0, check0); add_177482_2381377266(&result0, LOC6); res_532623_839829468 += ((NI) 1); } LA5: ; } } } break; case ((Tnodekind290020) 139): { Ropeobj177006* LOC12; NimStringDesc* LOC13; NimStringDesc* LOC14; Ropeobj177006* unionbody0; { if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)))) goto LA10; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_89)); } LA10: ; LOC12 = (Ropeobj177006*)0; LOC12 = genrecordfieldsaux_532421_839829468(m0, (*n0).kindU.S6.sons->data[((NI) 0)], accessexpr0, rectype0, check0); add_177482_2381377266(&result0, LOC12); LOC13 = (NimStringDesc*)0; LOC14 = (NimStringDesc*)0; LOC14 = mangle_526847_2036603609((*(*(*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s); LOC13 = rawNewString(LOC14->Sup.len + 1); appendString(LOC13, LOC14); appendChar(LOC13, 85); uname0 = rope_177277_2381377266(LOC13); { TY530811 LOC19; if (!!((accessexpr0 == NIM_NIL))) goto LA17; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = accessexpr0; LOC19[1] = uname0; ae0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC19, 2); } goto LA15; LA17: ; { ae0 = uname0; } LA15: ; unionbody0 = NIM_NIL; { NI i_532491_839829468; NI HEX3Atmp_532629_839829468; NI LOC22; NI res_532632_839829468; i_532491_839829468 = (NI)0; HEX3Atmp_532629_839829468 = (NI)0; LOC22 = (NI)0; LOC22 = sonslen_293351_850551059(n0); HEX3Atmp_532629_839829468 = (NI)(LOC22 - ((NI) 1)); res_532632_839829468 = ((NI) 1); { while (1) { if (!(res_532632_839829468 <= HEX3Atmp_532629_839829468)) goto LA24; i_532491_839829468 = res_532632_839829468; switch ((*(*n0).kindU.S6.sons->data[i_532491_839829468]).kind) { case ((Tnodekind290020) 85): case ((Tnodekind290020) 88): { k0 = lastson_293364_850551059((*n0).kindU.S6.sons->data[i_532491_839829468]); { Ropeobj177006* LOC30; TY530811 LOC31; Ropeobj177006* LOC32; if (!!(((*k0).kind == ((Tnodekind290020) 3)))) goto LA28; LOC30 = (Ropeobj177006*)0; LOC30 = rope_177401_2381377266(((NI64) (i_532491_839829468))); sname0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_91), LOC30); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = ae0; LOC31[1] = sname0; LOC32 = (Ropeobj177006*)0; LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC31, 2); a0 = genrecordfieldsaux_532421_839829468(m0, k0, LOC32, rectype0, check0); { TY177507 LOC37; if (!!((a0 == NIM_NIL))) goto LA35; add_177487_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_92)); add_177482_2381377266(&unionbody0, a0); memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = sname0; addf_178205_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_93), LOC37, 1); } LA35: ; } goto LA26; LA28: ; { Ropeobj177006* LOC39; LOC39 = (Ropeobj177006*)0; LOC39 = genrecordfieldsaux_532421_839829468(m0, k0, ae0, rectype0, check0); add_177482_2381377266(&unionbody0, LOC39); } LA26: ; } break; default: { internalerror_194113_155036129(((NimStringDesc*) &T839829468_94)); } break; } res_532632_839829468 += ((NI) 1); } LA24: ; } } { TY530811 LOC45; if (!!((unionbody0 == NIM_NIL))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = unionbody0; LOC45[1] = uname0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_95), LOC45, 2); } LA43: ; } break; case ((Tnodekind290020) 3): { field0 = (*n0).kindU.S4.sym; { if (!((*(*field0).typ).kind == ((Ttypekind290244) 62))) goto LA49; goto BeforeRet; } LA49: ; sname0 = manglerecfieldname_532361_839829468(field0, rectype0); { TY530811 LOC55; if (!!((accessexpr0 == NIM_NIL))) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = accessexpr0; LOC55[1] = sname0; ae0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC55, 2); } goto LA51; LA53: ; { ae0 = sname0; } LA51: ; fillloc_530282_839829468((&(*field0).loc), ((Tlockind290808) 5), (*field0).typ, ae0, ((Tstorageloc290812) 0)); { NIM_BOOL LOC59; Ttype290840* fieldtype0; LOC59 = (NIM_BOOL)0; LOC59 = isimportedcpptype_531478_839829468(rectype0); if (!!(LOC59)) goto LA60; fieldtype0 = skiptypes_294099_850551059((*field0).loc.t, IL64(211106232576256)); { NIM_BOOL LOC64; TY530811 LOC68; Ttype290840* LOC69; LOC64 = (NIM_BOOL)0; LOC64 = ((*fieldtype0).kind == ((Ttypekind290244) 16)); if (!(LOC64)) goto LA65; LOC64 = (((*fieldtype0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0); LA65: ; if (!LOC64) goto LA66; memset((void*)LOC68, 0, sizeof(LOC68)); LOC69 = (Ttype290840*)0; LOC69 = elemtype_318394_3876443242(fieldtype0); LOC68[0] = gettypedescaux_531505_839829468(m0, LOC69, check0); LOC68[1] = sname0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_97), LOC68, 2); } goto LA62; LA66: ; { TY530811 LOC73; if (!((*fieldtype0).kind == ((Ttypekind290244) 24))) goto LA71; memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = gettypedescweak_532079_839829468(m0, (*field0).loc.t, check0); LOC73[1] = sname0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC73, 2); } goto LA62; LA71: ; { TY533238 LOC77; NimStringDesc* LOC78; if (!!(((*field0).kindU.S4.bitsize == ((NI) 0)))) goto LA75; memset((void*)LOC77, 0, sizeof(LOC77)); LOC77[0] = gettypedescaux_531505_839829468(m0, (*field0).loc.t, check0); LOC77[1] = sname0; LOC78 = (NimStringDesc*)0; LOC78 = nimIntToStr((*field0).kindU.S4.bitsize); LOC77[2] = rope_177277_2381377266(LOC78); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_98), LOC77, 3); } goto LA62; LA75: ; { TY530811 LOC80; memset((void*)LOC80, 0, sizeof(LOC80)); LOC80[0] = gettypedescaux_531505_839829468(m0, (*field0).loc.t, check0); LOC80[1] = sname0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC80, 2); } LA62: ; } LA60: ; } break; default: { internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_99)); } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj177006*, getrecordfields_532636_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = genrecordfieldsaux_532421_839829468(m0, (*typ0).n, NIM_NIL, typ0, check0); return result0; } N_NIMCALL(Ropeobj177006*, getrecorddesc_532643_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0) { Ropeobj177006* result0; NIM_BOOL hasfield0; Ropeobj177006* attribute0; TY533238 LOC6; Ropeobj177006* desc0; NimStringDesc* LOC46; result0 = (Ropeobj177006*)0; hasfield0 = NIM_FALSE; { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 21))&31U)))!=0)) goto LA3; attribute0 = rope_177277_2381377266(Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field19); } goto LA1; LA3: ; { attribute0 = NIM_NIL; } LA1: ; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = structorunion_532001_839829468(typ0); LOC6[1] = name0; LOC6[2] = attribute0; result0 = ropecg_530407_839829468(m0, Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field18, LOC6, 3); { if (!((*typ0).kind == ((Ttypekind290244) 17))) goto LA9; { if (!((*typ0).sons->data[((NI) 0)] == NIM_NIL)) goto LA13; { NIM_BOOL LOC17; NIM_BOOL LOC18; TY531289 LOC23; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = !(((*typ0).sym == NIM_NIL)); if (!(LOC18)) goto LA19; LOC18 = (((*(*typ0).sym).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0); LA19: ; LOC17 = LOC18; if (LOC17) goto LA20; LOC17 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0); LA20: ; if (!LOC17) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_85), LOC23, 0); } goto LA15; LA21: ; { TY530811 LOC25; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = name0; LOC25[1] = attribute0; appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_86), LOC25, 2); hasfield0 = NIM_TRUE; } LA15: ; } goto LA11; LA13: ; { NIM_BOOL LOC27; TY177507 LOC31; Ttype290840* LOC32; LOC27 = (NIM_BOOL)0; LOC27 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC27) goto LA28; LOC27 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA28: ; if (!LOC27) goto LA29; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ttype290840*)0; LOC32 = skiptypes_294099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360)); LOC31[0] = gettypedescaux_531505_839829468(m0, LOC32, check0); appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_87), LOC31, 1); hasfield0 = NIM_TRUE; } goto LA11; LA29: ; { TY177507 LOC34; Ttype290840* LOC35; memset((void*)LOC34, 0, sizeof(LOC34)); LOC35 = (Ttype290840*)0; LOC35 = skiptypes_294099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360)); LOC34[0] = gettypedescaux_531505_839829468(m0, LOC35, check0); appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_88), LOC34, 1); hasfield0 = NIM_TRUE; } LA11: ; } goto LA7; LA9: ; { TY177507 LOC37; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = name0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_85), LOC37, 1); } LA7: ; desc0 = getrecordfields_532636_839829468(m0, typ0, check0); { NIM_BOOL LOC40; TY531289 LOC44; LOC40 = (NIM_BOOL)0; LOC40 = (desc0 == NIM_NIL); if (!(LOC40)) goto LA41; LOC40 = !(hasfield0); LA41: ; if (!LOC40) goto LA42; memset((void*)LOC44, 0, sizeof(LOC44)); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_100), LOC44, 0); } goto LA38; LA42: ; { add_177482_2381377266(&result0, desc0); } LA38: ; LOC46 = (NimStringDesc*)0; LOC46 = rawNewString(tnl_175644_4151366050->Sup.len + 2); appendString(LOC46, ((NimStringDesc*) &T839829468_101)); appendString(LOC46, tnl_175644_4151366050); add_177487_2381377266(&result0, LOC46); return result0; } N_NIMCALL(Ropeobj177006*, gettupledesc_532777_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0) { Ropeobj177006* result0; TY530811 LOC1; Ropeobj177006* desc0; NimStringDesc* LOC13; result0 = (Ropeobj177006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = structorunion_532001_839829468(typ0); LOC1[1] = name0; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_102), LOC1, 2); desc0 = NIM_NIL; { NI i_532799_839829468; NI HEX3Atmp_532820_839829468; NI LOC3; NI res_532823_839829468; i_532799_839829468 = (NI)0; HEX3Atmp_532820_839829468 = (NI)0; LOC3 = (NI)0; LOC3 = sonslen_293327_850551059(typ0); HEX3Atmp_532820_839829468 = (NI)(LOC3 - ((NI) 1)); res_532823_839829468 = ((NI) 0); { while (1) { TY530811 LOC6; if (!(res_532823_839829468 <= HEX3Atmp_532820_839829468)) goto LA5; i_532799_839829468 = res_532823_839829468; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = gettypedescaux_531505_839829468(m0, (*typ0).sons->data[i_532799_839829468], check0); LOC6[1] = rope_177401_2381377266(((NI64) (i_532799_839829468))); addf_178205_2381377266(&desc0, ((NimStringDesc*) &T839829468_103), LOC6, 2); res_532823_839829468 += ((NI) 1); } LA5: ; } } { NimStringDesc* LOC11; if (!(desc0 == NIM_NIL)) goto LA9; LOC11 = (NimStringDesc*)0; LOC11 = rawNewString(tnl_175644_4151366050->Sup.len + 11); appendString(LOC11, ((NimStringDesc*) &T839829468_104)); appendString(LOC11, tnl_175644_4151366050); add_177487_2381377266(&result0, LOC11); } goto LA7; LA9: ; { add_177482_2381377266(&result0, desc0); } LA7: ; LOC13 = (NimStringDesc*)0; LOC13 = rawNewString(tnl_175644_4151366050->Sup.len + 2); appendString(LOC13, ((NimStringDesc*) &T839829468_101)); appendString(LOC13, tnl_175644_4151366050); add_177487_2381377266(&result0, LOC13); return result0; } N_NIMCALL(Ropeobj177006*, gettypedescaux_531505_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0) { Ropeobj177006* result0; Ttype290840* t_532942_839829468; { result0 = (Ropeobj177006*)0; t_532942_839829468 = getuniquetype_526640_2036603609(typ0); { if (!(t_532942_839829468 == NIM_NIL)) goto LA3; internalerror_194113_155036129(((NimStringDesc*) &T839829468_27)); } LA3: ; { if (!!(((*t_532942_839829468).sym == NIM_NIL))) goto LA7; useheader_530369_839829468(m0, (*t_532942_839829468).sym); } LA7: ; result0 = gettypepre_531972_839829468(m0, t_532942_839829468); { if (!!((result0 == NIM_NIL))) goto LA11; goto BeforeRet; } LA11: ; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = containsorincl_266862_2627731572(check0, (*t_532942_839829468).Sup.id); if (!LOC15) goto LA16; { NIM_BOOL LOC20; NimStringDesc* LOC24; NimStringDesc* LOC25; LOC20 = (NIM_BOOL)0; LOC20 = isimportedcpptype_531478_839829468(typ0); if (LOC20) goto LA21; LOC20 = isimportedcpptype_531478_839829468(t_532942_839829468); LA21: ; if (!!(LOC20)) goto LA22; LOC24 = (NimStringDesc*)0; LOC25 = (NimStringDesc*)0; LOC25 = typetostring_318017_3876443242(typ0, ((Tprefereddesc318011) 0)); LOC24 = rawNewString(LOC25->Sup.len + 28); appendString(LOC24, ((NimStringDesc*) &T839829468_51)); appendString(LOC24, LOC25); internalerror_194113_155036129(LOC24); } LA22: ; } LA16: ; switch ((*t_532942_839829468).kind) { case ((Ttypekind290244) 22): case ((Ttypekind290244) 21): case ((Ttypekind290244) 23): { NimStringDesc* star0; Ttype290840* et0; Ttype290840* LOC38; Ttype290840* etb0; { NIM_BOOL LOC29; NIM_BOOL LOC30; NIM_BOOL LOC33; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((*t_532942_839829468).kind == ((Ttypekind290244) 23)); if (!(LOC30)) goto LA31; LOC30 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0)); LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA32; LOC33 = (NIM_BOOL)0; LOC33 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC33) goto LA34; LOC33 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA34: ; LOC29 = LOC33; LA32: ; if (!LOC29) goto LA35; star0 = copyString(((NimStringDesc*) &T839829468_52)); } goto LA27; LA35: ; { star0 = copyString(((NimStringDesc*) &T839829468_53)); } LA27: ; LOC38 = (Ttype290840*)0; LOC38 = skiptypes_294099_850551059(typ0, IL64(211106232576256)); et0 = lastson_293377_850551059(LOC38); etb0 = skiptypes_294099_850551059(et0, IL64(211106232576256)); { if (!((IL64(281475110993936) &((NU64)1<<((NU)((*etb0).kind)&63U)))!=0)) goto LA41; et0 = elemtype_318394_3876443242(etb0); etb0 = skiptypes_294099_850551059(et0, IL64(211106232576256)); star0->data[((NI) 0)] = 42; } LA41: ; switch ((*etb0).kind) { case ((Ttypekind290244) 17): case ((Ttypekind290244) 18): { { NIM_BOOL LOC46; Ropeobj177006* LOC50; LOC46 = (NIM_BOOL)0; LOC46 = isimportedcpptype_531478_839829468(etb0); if (!(LOC46)) goto LA47; LOC46 = ((*et0).kind == ((Ttypekind290244) 11)); LA47: ; if (!LOC46) goto LA48; LOC50 = (Ropeobj177006*)0; LOC50 = gettypedescaux_531505_839829468(m0, et0, check0); result0 = HEX26_177447_2381377266(LOC50, star0); } goto LA44; LA48: ; { Ttype290840* x0; Ropeobj177006* name0; Tidobj197004* LOC52; TNimObject* LOC53; x0 = getuniquetype_526640_2036603609(etb0); name0 = gettypeforward_532039_839829468(m0, x0); result0 = HEX26_177447_2381377266(name0, star0); LOC52 = (Tidobj197004*)0; LOC52 = &t_532942_839829468->Sup; LOC53 = (TNimObject*)0; LOC53 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC52, LOC53); pushtype_531958_839829468(m0, x0); } LA44: ; } break; case ((Ttypekind290244) 24): { Ttype290840* x0; Ropeobj177006* name0; Ropeobj177006* LOC55; Tidobj197004* LOC56; TNimObject* LOC57; x0 = getuniquetype_526640_2036603609(etb0); name0 = gettypeforward_532039_839829468(m0, x0); LOC55 = (Ropeobj177006*)0; LOC55 = HEX26_177447_2381377266(name0, ((NimStringDesc*) &T839829468_53)); result0 = HEX26_177447_2381377266(LOC55, star0); LOC56 = (Tidobj197004*)0; LOC56 = &t_532942_839829468->Sup; LOC57 = (TNimObject*)0; LOC57 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC56, LOC57); pushtype_531958_839829468(m0, x0); } break; default: { Ropeobj177006* LOC59; Tidobj197004* LOC60; TNimObject* LOC61; LOC59 = (Ropeobj177006*)0; LOC59 = gettypedescaux_531505_839829468(m0, et0, check0); result0 = HEX26_177447_2381377266(LOC59, star0); LOC60 = (Tidobj197004*)0; LOC60 = &t_532942_839829468->Sup; LOC61 = (TNimObject*)0; LOC61 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC60, LOC61); } break; } } break; case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { Ropeobj177006* LOC63; Tidobj197004* LOC64; TNimObject* LOC65; LOC63 = (Ropeobj177006*)0; LOC63 = gettypedescweak_532079_839829468(m0, (*t_532942_839829468).sons->data[((NI) 0)], check0); result0 = HEX26_177447_2381377266(LOC63, ((NimStringDesc*) &T839829468_53)); LOC64 = (Tidobj197004*)0; LOC64 = &t_532942_839829468->Sup; LOC65 = (TNimObject*)0; LOC65 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC64, LOC65); } break; case ((Ttypekind290244) 20): case ((Ttypekind290244) 14): { Ttype290840* t0; { if (!((*t_532942_839829468).kind == ((Ttypekind290244) 20))) goto LA69; t0 = lastson_293377_850551059(t_532942_839829468); } goto LA67; LA69: ; { t0 = t_532942_839829468; } LA67: ; result0 = cachegettype_531593_839829468((*m0).typecache, t0); { if (!(result0 == NIM_NIL)) goto LA74; result0 = gettypename_531313_839829468(t0); { NIM_BOOL LOC78; NIM_BOOL LOC80; Tidobj197004* LOC84; TNimObject* LOC85; NI size0; NU32 owner0; LOC78 = (NIM_BOOL)0; LOC78 = isimportedcpptype_531478_839829468(t0); if (LOC78) goto LA79; LOC80 = (NIM_BOOL)0; LOC80 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0); if (!(LOC80)) goto LA81; LOC80 = ((*(*t0).sym).magic == ((Tmagic290524) 0)); LA81: ; LOC78 = LOC80; LA79: ; if (!!(LOC78)) goto LA82; LOC84 = (Tidobj197004*)0; LOC84 = &t0->Sup; LOC85 = (TNimObject*)0; LOC85 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC84, LOC85); size0 = (NI)0; { NI64 LOC88; TY177507 LOC91; LOC88 = (NI64)0; LOC88 = firstord_318001_3876443242(t0); if (!(LOC88 < IL64(0))) goto LA89; memset((void*)LOC91, 0, sizeof(LOC91)); LOC91[0] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC91, 1); size0 = ((NI) 4); } goto LA86; LA89: ; { NI64 LOC93; LOC93 = (NI64)0; LOC93 = getsize_318135_3876443242(t0); size0 = ((NI) (LOC93)); switch (size0) { case ((NI) 1): { TY177507 LOC95; memset((void*)LOC95, 0, sizeof(LOC95)); LOC95[0] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_60), LOC95, 1); } break; case ((NI) 2): { TY177507 LOC97; memset((void*)LOC97, 0, sizeof(LOC97)); LOC97[0] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_61), LOC97, 1); } break; case ((NI) 4): { TY177507 LOC99; memset((void*)LOC99, 0, sizeof(LOC99)); LOC99[0] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC99, 1); } break; case ((NI) 8): { TY177507 LOC101; memset((void*)LOC101, 0, sizeof(LOC101)); LOC101[0] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_62), LOC101, 1); } break; default: { internalerror_194100_155036129((*(*t0).sym).info, ((NimStringDesc*) &T839829468_63)); } break; } } LA86: ; owner0 = hashowner_530977_839829468((*t0).sym); { NIM_BOOL LOC105; TY201017* vals0; Enumdesc201007 LOC114; LOC105 = (NIM_BOOL)0; LOC105 = hasenum_201230_1926258066((&gdebuginfo_201470_1926258066), (*(*(*t0).sym).name).s, ((NI) ((*(*t0).sym).info.line)), owner0); if (!!(LOC105)) goto LA106; vals0 = (TY201017*) newSeq((&NTI201017), 0); { NI i_533144_839829468; NI HEX3Atmp_533649_839829468; NI LOC109; NI res_533652_839829468; i_533144_839829468 = (NI)0; HEX3Atmp_533649_839829468 = (NI)0; LOC109 = (NI)0; LOC109 = len_291081_850551059((*t0).n); HEX3Atmp_533649_839829468 = (NI)(LOC109 - ((NI) 1)); res_533652_839829468 = ((NI) 0); { while (1) { Tsym290834* field0; TY201018 LOC112; NimStringDesc* LOC113; if (!(res_533652_839829468 <= HEX3Atmp_533649_839829468)) goto LA111; i_533144_839829468 = res_533652_839829468; field0 = (*(*(*t0).n).kindU.S6.sons->data[i_533144_839829468]).kindU.S4.sym; memset((void*)(&LOC112), 0, sizeof(LOC112)); LOC112.Field0 = copyString((*(*field0).name).s); LOC112.Field1 = (*field0).position; vals0 = (TY201017*) incrSeqV2(&(vals0)->Sup, sizeof(TY201018)); LOC113 = (NimStringDesc*)0; LOC113 = vals0->data[vals0->Sup.len].Field0; vals0->data[vals0->Sup.len].Field0 = copyStringRC1(LOC112.Field0); if (LOC113) nimGCunrefNoCycle(LOC113); vals0->data[vals0->Sup.len].Field1 = LOC112.Field1; ++vals0->Sup.len; res_533652_839829468 += ((NI) 1); } LA111: ; } } memset((void*)(&LOC114), 0, sizeof(LOC114)); memset((void*)(&LOC114), 0, sizeof(LOC114)); LOC114.size = size0; LOC114.owner = owner0; LOC114.id = (*(*t0).sym).Sup.id; LOC114.name = copyString((*(*(*t0).sym).name).s); genericSeqAssign((&LOC114.values), vals0, (&NTI201017)); registerenum_201419_1926258066((&gdebuginfo_201470_1926258066), (&LOC114)); } LA106: ; } LA82: ; } LA74: ; } break; case ((Ttypekind290244) 25): { Tidobj197004* LOC116; TNimObject* LOC117; Ropeobj177006* rettype0; Ropeobj177006* desc0; result0 = gettypename_531313_839829468(t_532942_839829468); LOC116 = (Tidobj197004*)0; LOC116 = &t_532942_839829468->Sup; LOC117 = (TNimObject*)0; LOC117 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC116, LOC117); rettype0 = (Ropeobj177006*)0; desc0 = (Ropeobj177006*)0; genprocparams_532115_839829468(m0, t_532942_839829468, &rettype0, &desc0, check0, NIM_TRUE, NIM_TRUE); { NIM_BOOL LOC120; LOC120 = (NIM_BOOL)0; LOC120 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC120)) goto LA121; { TY533235 LOC127; if (!!(((*t_532942_839829468).callconv == ((Tcallingconvention290002) 8)))) goto LA125; memset((void*)LOC127, 0, sizeof(LOC127)); LOC127[0] = rope_177277_2381377266(Callingconvtostr_531587_839829468[((*t_532942_839829468).callconv)- 0]); LOC127[1] = rettype0; LOC127[2] = result0; LOC127[3] = desc0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC127, 4); } goto LA123; LA125: ; { TY533238 LOC129; memset((void*)LOC129, 0, sizeof(LOC129)); LOC129[0] = result0; LOC129[1] = rettype0; LOC129[2] = desc0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC129, 3); } LA123: ; } LA121: ; } break; case ((Ttypekind290244) 24): { Tidobj197004* LOC144; Ropeobj177006* LOC145; TNimObject* LOC146; result0 = cachegettype_531593_839829468((*m0).forwtypecache, t_532942_839829468); { Tidobj197004* LOC142; TNimObject* LOC143; if (!(result0 == NIM_NIL)) goto LA133; result0 = gettypename_531313_839829468(t_532942_839829468); { NIM_BOOL LOC137; NimStringDesc* LOC140; TY530811 LOC141; LOC137 = (NIM_BOOL)0; LOC137 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC137)) goto LA138; LOC140 = (NimStringDesc*)0; LOC140 = getforwardstructformat_532015_839829468(m0); memset((void*)LOC141, 0, sizeof(LOC141)); LOC141[0] = structorunion_532001_839829468(t_532942_839829468); LOC141[1] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 2))- 0], LOC140, LOC141, 2); } LA138: ; LOC142 = (Tidobj197004*)0; LOC142 = &t_532942_839829468->Sup; LOC143 = (TNimObject*)0; LOC143 = &result0->Sup; idtableput_297094_2984716966((&(*m0).forwtypecache), LOC142, LOC143); } LA133: ; LOC144 = (Tidobj197004*)0; LOC144 = &t_532942_839829468->Sup; LOC145 = (Ropeobj177006*)0; LOC145 = HEX26_177447_2381377266(result0, ((NimStringDesc*) &T839829468_53)); LOC146 = (TNimObject*)0; LOC146 = &LOC145->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC144, LOC146); { NIM_BOOL LOC149; LOC149 = (NIM_BOOL)0; LOC149 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC149)) goto LA150; { Ttype290840* LOC154; NimStringDesc* LOC157; NimStringDesc* LOC158; TY530811 LOC166; LOC154 = (Ttype290840*)0; LOC154 = skiptypes_294099_850551059((*t_532942_839829468).sons->data[((NI) 0)], IL64(211106232576256)); if (!!(((*LOC154).kind == ((Ttypekind290244) 3)))) goto LA155; LOC157 = (NimStringDesc*)0; LOC158 = (NimStringDesc*)0; { NIM_BOOL LOC161; LOC161 = (NIM_BOOL)0; LOC161 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC161) goto LA162; LOC161 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA162: ; if (!LOC161) goto LA163; LOC158 = copyString(((NimStringDesc*) &T839829468_76)); } goto LA159; LA163: ; { LOC158 = copyString(((NimStringDesc*) &T839829468_77)); } LA159: ; LOC157 = rawNewString(LOC158->Sup.len + 31); appendString(LOC157, LOC158); appendString(LOC157, ((NimStringDesc*) &T839829468_78)); memset((void*)LOC166, 0, sizeof(LOC166)); LOC166[0] = gettypedescaux_531505_839829468(m0, (*t_532942_839829468).sons->data[((NI) 0)], check0); LOC166[1] = result0; appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 4))- 0], LOC157, LOC166, 2); } goto LA152; LA155: ; { result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_79)); } LA152: ; } LA150: ; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_53)); } break; case ((Ttypekind290244) 4): case ((Ttypekind290244) 16): { NI64 n0; Tidobj197004* LOC173; TNimObject* LOC174; n0 = lengthord_318007_3876443242(t_532942_839829468); { if (!(n0 <= IL64(0))) goto LA171; n0 = IL64(1); } LA171: ; result0 = gettypename_531313_839829468(t_532942_839829468); LOC173 = (Tidobj197004*)0; LOC173 = &t_532942_839829468->Sup; LOC174 = (TNimObject*)0; LOC174 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC173, LOC174); { NIM_BOOL LOC177; Ropeobj177006* foo0; TY533238 LOC180; LOC177 = (NIM_BOOL)0; LOC177 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC177)) goto LA178; foo0 = gettypedescaux_531505_839829468(m0, (*t_532942_839829468).sons->data[((NI) 1)], check0); memset((void*)LOC180, 0, sizeof(LOC180)); LOC180[0] = foo0; LOC180[1] = result0; LOC180[2] = rope_177401_2381377266(n0); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_80), LOC180, 3); } LA178: ; } break; case ((Ttypekind290244) 17): case ((Ttypekind290244) 18): { { NIM_BOOL LOC184; Ropeobj177006* cppname0; NI i0; NI chunkstart0; Ropeobj177006* LOC226; LOC184 = (NIM_BOOL)0; LOC184 = isimportedcpptype_531478_839829468(t_532942_839829468); if (!(LOC184)) goto LA185; LOC184 = ((*typ0).kind == ((Ttypekind290244) 11)); LA185: ; if (!LOC184) goto LA186; cppname0 = gettypename_531313_839829468(t_532942_839829468); i0 = ((NI) 0); chunkstart0 = ((NI) 0); { while (1) { if (!(i0 < ((*cppname0).data ? (*cppname0).data->Sup.len : 0))) goto LA189; { NI chunkend0; NI idx0; NI stars0; if (!((NU8)((*cppname0).data->data[i0]) == (NU8)(39))) goto LA192; chunkend0 = (i0 - 1); idx0 = (NI)0; stars0 = (NI)0; { NIM_BOOL LOC196; NimStringDesc* LOC199; Ttype290840* typeinslot0; LOC196 = (NIM_BOOL)0; LOC196 = scancppgenericslot_532827_839829468((*cppname0).data, (&i0), (&idx0), (&stars0)); if (!LOC196) goto LA197; LOC199 = (NimStringDesc*)0; LOC199 = copyStrLast((*cppname0).data, chunkstart0, chunkend0); add_177487_2381377266(&result0, LOC199); chunkstart0 = i0; typeinslot0 = resolvestarsincpptype_532891_839829468(typ0, (NI)(idx0 + ((NI) 1)), stars0); { NIM_BOOL LOC202; TY531289 LOC206; Ropeobj177006* LOC207; LOC202 = (NIM_BOOL)0; LOC202 = (typeinslot0 == NIM_NIL); if (LOC202) goto LA203; LOC202 = ((*typeinslot0).kind == ((Ttypekind290244) 62)); LA203: ; if (!LOC202) goto LA204; memset((void*)LOC206, 0, sizeof(LOC206)); LOC207 = (Ropeobj177006*)0; LOC207 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_26), LOC206, 0); add_177482_2381377266(&result0, LOC207); } goto LA200; LA204: ; { Ropeobj177006* LOC209; LOC209 = (Ropeobj177006*)0; LOC209 = gettypedescaux_531505_839829468(m0, typeinslot0, check0); add_177482_2381377266(&result0, LOC209); } LA200: ; } LA197: ; } goto LA190; LA192: ; { i0 += ((NI) 1); } LA190: ; } LA189: ; } { NimStringDesc* LOC215; if (!!((chunkstart0 == ((NI) 0)))) goto LA213; LOC215 = (NimStringDesc*)0; LOC215 = copyStr((*cppname0).data, chunkstart0); add_177487_2381377266(&result0, LOC215); } goto LA211; LA213: ; { result0 = HEX26_177447_2381377266(cppname0, ((NimStringDesc*) &T839829468_82)); { NI i_533516_839829468; NI HEX3Atmp_533665_839829468; NI LOC218; NI res_533668_839829468; i_533516_839829468 = (NI)0; HEX3Atmp_533665_839829468 = (NI)0; LOC218 = (NI)0; LOC218 = len_293339_850551059(typ0); HEX3Atmp_533665_839829468 = (NI)(LOC218 - ((NI) 2)); res_533668_839829468 = ((NI) 1); { while (1) { Ropeobj177006* LOC225; if (!(res_533668_839829468 <= HEX3Atmp_533665_839829468)) goto LA220; i_533516_839829468 = res_533668_839829468; { if (!(((NI) 1) < i_533516_839829468)) goto LA223; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_83)); } LA223: ; LOC225 = (Ropeobj177006*)0; LOC225 = gettypedescaux_531505_839829468(m0, (*typ0).sons->data[i_533516_839829468], check0); add_177482_2381377266(&result0, LOC225); res_533668_839829468 += ((NI) 1); } LA220: ; } } add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_84)); } LA211: ; LOC226 = (Ropeobj177006*)0; LOC226 = getrecorddesc_532643_839829468(m0, t_532942_839829468, result0, check0); } goto LA182; LA186: ; { Tidobj197004* LOC241; TNimObject* LOC242; Ropeobj177006* recdesc0; result0 = cachegettype_531593_839829468((*m0).forwtypecache, t_532942_839829468); { Tidobj197004* LOC239; TNimObject* LOC240; if (!(result0 == NIM_NIL)) goto LA230; result0 = gettypename_531313_839829468(t_532942_839829468); { NIM_BOOL LOC234; NimStringDesc* LOC237; TY530811 LOC238; LOC234 = (NIM_BOOL)0; LOC234 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC234)) goto LA235; LOC237 = (NimStringDesc*)0; LOC237 = getforwardstructformat_532015_839829468(m0); memset((void*)LOC238, 0, sizeof(LOC238)); LOC238[0] = structorunion_532001_839829468(t_532942_839829468); LOC238[1] = result0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 2))- 0], LOC237, LOC238, 2); } LA235: ; LOC239 = (Tidobj197004*)0; LOC239 = &t_532942_839829468->Sup; LOC240 = (TNimObject*)0; LOC240 = &result0->Sup; idtableput_297094_2984716966((&(*m0).forwtypecache), LOC239, LOC240); } LA230: ; LOC241 = (Tidobj197004*)0; LOC241 = &t_532942_839829468->Sup; LOC242 = (TNimObject*)0; LOC242 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC241, LOC242); { if (!!(((*t_532942_839829468).kind == ((Ttypekind290244) 18)))) goto LA245; recdesc0 = getrecorddesc_532643_839829468(m0, t_532942_839829468, result0, check0); } goto LA243; LA245: ; { recdesc0 = gettupledesc_532777_839829468(m0, t_532942_839829468, result0, check0); } LA243: ; { NIM_BOOL LOC250; LOC250 = (NIM_BOOL)0; LOC250 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC250)) goto LA251; add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], recdesc0); } LA251: ; } LA182: ; } break; case ((Ttypekind290244) 19): { Ttype290840* LOC254; Ropeobj177006* LOC255; Tidobj197004* LOC256; TNimObject* LOC257; LOC254 = (Ttype290840*)0; LOC254 = lastson_293377_850551059(t_532942_839829468); LOC255 = (Ropeobj177006*)0; LOC255 = gettypename_531313_839829468(LOC254); result0 = HEX26_177447_2381377266(LOC255, ((NimStringDesc*) &T839829468_105)); LOC256 = (Tidobj197004*)0; LOC256 = &t_532942_839829468->Sup; LOC257 = (TNimObject*)0; LOC257 = &result0->Sup; idtableput_297094_2984716966((&(*m0).typecache), LOC256, LOC257); { NIM_BOOL LOC260; NI s0; NI64 LOC263; LOC260 = (NIM_BOOL)0; LOC260 = isimportedtype_531451_839829468(t_532942_839829468); if (!!(LOC260)) goto LA261; LOC263 = (NI64)0; LOC263 = getsize_318135_3876443242(t_532942_839829468); s0 = ((NI) (LOC263)); switch (s0) { case ((NI) 1): case ((NI) 2): case ((NI) 4): case ((NI) 8): { TY530811 LOC265; memset((void*)LOC265, 0, sizeof(LOC265)); LOC265[0] = result0; LOC265[1] = rope_177401_2381377266(((NI64) ((NI)(s0 * ((NI) 8))))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_106), LOC265, 2); } break; default: { TY530811 LOC267; NI64 LOC268; memset((void*)LOC267, 0, sizeof(LOC267)); LOC267[0] = result0; LOC268 = (NI64)0; LOC268 = getsize_318135_3876443242(t_532942_839829468); LOC267[1] = rope_177401_2381377266(LOC268); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_107), LOC267, 2); } break; } } LA261: ; } break; case ((Ttypekind290244) 11): case ((Ttypekind290244) 13): case ((Ttypekind290244) 15): case ((Ttypekind290244) 46): case ((Ttypekind290244) 47): case ((Ttypekind290244) 49): case ((Ttypekind290244) 8): { Ttype290840* LOC270; LOC270 = (Ttype290840*)0; LOC270 = lastson_293377_850551059(t_532942_839829468); result0 = gettypedescaux_531505_839829468(m0, LOC270, check0); } break; default: { NimStringDesc* LOC272; LOC272 = (NimStringDesc*)0; LOC272 = rawNewString(reprEnum((NI)(*t_532942_839829468).kind, (&NTI290244))->Sup.len + 16); appendString(LOC272, ((NimStringDesc*) &T839829468_108)); appendString(LOC272, reprEnum((NI)(*t_532942_839829468).kind, (&NTI290244))); appendChar(LOC272, 41); internalerror_194113_155036129(LOC272); result0 = NIM_NIL; } break; } excl_266841_2627731572(check0, (*t_532942_839829468).Sup.id); }BeforeRet: ; return result0; } static N_INLINE(NIM_BOOL, iscompiletimeonly_326706_3876443242)(Ttype290840* t0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((IL64(576460752303423744) &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); return result0; } N_NIMCALL(Tstorageloc290812, paramstorageloc_532098_839829468)(Tsym290834* param0) { Tstorageloc290812 result0; result0 = (Tstorageloc290812)0; { Ttype290840* LOC3; LOC3 = (Ttype290840*)0; LOC3 = skiptypes_294099_850551059((*param0).typ, 8388864); if (!!(((IL64(281475110993936) &((NU64)1<<((NU)((*LOC3).kind)&63U)))!=0))) goto LA4; result0 = ((Tstorageloc290812) 2); } goto LA1; LA4: ; { result0 = ((Tstorageloc290812) 0); } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, ccgintroducedptr_531611_839829468)(Tsym290834* s0) { NIM_BOOL result0; Ttype290840* pt0; { result0 = (NIM_BOOL)0; pt0 = skiptypes_294099_850551059((*s0).typ, IL64(211106232576256)); { if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag290431) 13))&31U)))!=0)) goto LA3; result0 = NIM_TRUE; goto BeforeRet; } goto LA1; LA3: ; { if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag290431) 12))&31U)))!=0)) goto LA6; result0 = NIM_FALSE; goto BeforeRet; } goto LA1; LA6: ; LA1: ; switch ((*pt0).kind) { case ((Ttypekind290244) 17): { { NIM_BOOL LOC11; NI64 LOC13; LOC11 = (NIM_BOOL)0; LOC11 = (((*s0).options &(1U<<((NU)(((Toption168009) 18))&31U)))!=0); if (LOC11) goto LA12; LOC13 = (NI64)0; LOC13 = getsize_318135_3876443242(pt0); LOC11 = (((NI64) ((NI)(floatsize_175642_4151366050 * ((NI) 2)))) < LOC13); LA12: ; if (!LOC11) goto LA14; result0 = NIM_TRUE; } goto LA9; LA14: ; { NIM_BOOL LOC17; LOC17 = (NIM_BOOL)0; LOC17 = (((*pt0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0); if (!(LOC17)) goto LA18; LOC17 = ((*pt0).sons->data[((NI) 0)] == NIM_NIL); LA18: ; if (!LOC17) goto LA19; result0 = NIM_FALSE; } goto LA9; LA19: ; { result0 = NIM_TRUE; } LA9: ; } break; case ((Ttypekind290244) 18): { NIM_BOOL LOC23; NI64 LOC24; LOC23 = (NIM_BOOL)0; LOC24 = (NI64)0; LOC24 = getsize_318135_3876443242(pt0); LOC23 = (((NI64) ((NI)(floatsize_175642_4151366050 * ((NI) 2)))) < LOC24); if (LOC23) goto LA25; LOC23 = (((*s0).options &(1U<<((NU)(((Toption168009) 18))&31U)))!=0); LA25: ; result0 = LOC23; } break; default: { result0 = NIM_FALSE; } break; } }BeforeRet: ; return result0; } N_NIMCALL(Tctypekind527007, mapreturntype_531447_839829468)(Ttype290840* typ0) { Tctypekind527007 result0; result0 = (Tctypekind527007)0; result0 = maptype_531394_839829468(typ0); return result0; } N_NIMCALL(void, genprocparams_532115_839829468)(Tcgen527027* m0, Ttype290840* t0, Ropeobj177006** rettype0, Ropeobj177006** params0, Intset266030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0) { unsureAsgnRef((void**) (&(*params0)), NIM_NIL); { NIM_BOOL LOC3; TY531289 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).sons->data[((NI) 0)] == NIM_NIL); if (LOC3) goto LA4; LOC3 = isinvalidreturntype_531550_839829468((*t0).sons->data[((NI) 0)]); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); unsureAsgnRef((void**) (&(*rettype0)), HEX25_177905_2381377266(((NimStringDesc*) &T839829468_26), LOC7, 0)); } goto LA1; LA5: ; { unsureAsgnRef((void**) (&(*rettype0)), gettypedescaux_531505_839829468(m0, (*t0).sons->data[((NI) 0)], check0)); } LA1: ; { NI i_532152_839829468; NI HEX3Atmp_532353_839829468; NI LOC10; NI res_532356_839829468; i_532152_839829468 = (NI)0; HEX3Atmp_532353_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = sonslen_293351_850551059((*t0).n); HEX3Atmp_532353_839829468 = (NI)(LOC10 - ((NI) 1)); res_532356_839829468 = ((NI) 1); { while (1) { if (!(res_532356_839829468 <= HEX3Atmp_532353_839829468)) goto LA12; i_532152_839829468 = res_532356_839829468; { Tsym290834* param0; Ropeobj177006* LOC29; Tstorageloc290812 LOC30; TY531289 LOC45; Ropeobj177006* LOC46; Ttype290840* arr0; NI j0; { if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_532152_839829468]).kind == ((Tnodekind290020) 3)))) goto LA16; internalerror_194100_155036129((*(*t0).n).info, ((NimStringDesc*) &T839829468_109)); } LA16: ; param0 = (*(*(*t0).n).kindU.S6.sons->data[i_532152_839829468]).kindU.S4.sym; { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = iscompiletimeonly_326706_3876443242((*param0).typ); if (!LOC20) goto LA21; goto LA13; } LA21: ; { TY531289 LOC27; Ropeobj177006* LOC28; if (!!(((*params0) == NIM_NIL))) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Ropeobj177006*)0; LOC28 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC27, 0); add_177482_2381377266(params0, LOC28); } LA25: ; LOC29 = (Ropeobj177006*)0; LOC29 = manglename_531205_839829468(param0); LOC30 = (Tstorageloc290812)0; LOC30 = paramstorageloc_532098_839829468(param0); fillloc_530282_839829468((&(*param0).loc), ((Tlockind290808) 4), (*param0).typ, LOC29, LOC30); { NIM_BOOL LOC33; Ropeobj177006* LOC36; TY531289 LOC37; Ropeobj177006* LOC38; LOC33 = (NIM_BOOL)0; LOC33 = ccgintroducedptr_531611_839829468(param0); if (!LOC33) goto LA34; LOC36 = (Ropeobj177006*)0; LOC36 = gettypedescweak_532079_839829468(m0, (*param0).typ, check0); add_177482_2381377266(params0, LOC36); memset((void*)LOC37, 0, sizeof(LOC37)); LOC38 = (Ropeobj177006*)0; LOC38 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_53), LOC37, 0); add_177482_2381377266(params0, LOC38); (*param0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 0))%(sizeof(NU16)*8)); (*param0).loc.s = ((Tstorageloc290812) 0); } goto LA31; LA34: ; { Ropeobj177006* LOC42; if (!weakdep0) goto LA40; LOC42 = (Ropeobj177006*)0; LOC42 = gettypedescweak_532079_839829468(m0, (*param0).typ, check0); add_177482_2381377266(params0, LOC42); } goto LA31; LA40: ; { Ropeobj177006* LOC44; LOC44 = (Ropeobj177006*)0; LOC44 = gettypedescaux_531505_839829468(m0, (*param0).typ, check0); add_177482_2381377266(params0, LOC44); } LA31: ; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (Ropeobj177006*)0; LOC46 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC45, 0); add_177482_2381377266(params0, LOC46); add_177482_2381377266(params0, (*param0).loc.r); arr0 = (*param0).typ; { if (!((*arr0).kind == ((Ttypekind290244) 23))) goto LA49; arr0 = (*arr0).sons->data[((NI) 0)]; } LA49: ; j0 = ((NI) 0); { while (1) { TY530811 LOC57; if (!((IL64(281475110928384) &((NU64)1<<((NU)((*arr0).kind)&63U)))!=0)) goto LA52; { if (!((*(*param0).typ).kind == ((Ttypekind290244) 23))) goto LA55; (*param0).loc.s = ((Tstorageloc290812) 0); } LA55: ; memset((void*)LOC57, 0, sizeof(LOC57)); LOC57[0] = (*param0).loc.r; LOC57[1] = rope_177401_2381377266(((NI64) (j0))); addf_178205_2381377266(params0, ((NimStringDesc*) &T839829468_112), LOC57, 2); j0 += ((NI) 1); arr0 = (*arr0).sons->data[((NI) 0)]; } LA52: ; } } LA13: ; res_532356_839829468 += ((NI) 1); } LA12: ; } } { NIM_BOOL LOC60; Ttype290840* arr0; TY531289 LOC76; LOC60 = (NIM_BOOL)0; LOC60 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); if (!(LOC60)) goto LA61; LOC60 = isinvalidreturntype_531550_839829468((*t0).sons->data[((NI) 0)]); LA61: ; if (!LOC60) goto LA62; arr0 = (*t0).sons->data[((NI) 0)]; { if (!!(((*params0) == NIM_NIL))) goto LA66; add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA66: ; { Tctypekind527007 LOC70; Ropeobj177006* LOC73; LOC70 = (Tctypekind527007)0; LOC70 = mapreturntype_531447_839829468((*t0).sons->data[((NI) 0)]); if (!!((LOC70 == ((Tctypekind527007) 17)))) goto LA71; LOC73 = (Ropeobj177006*)0; LOC73 = gettypedescweak_532079_839829468(m0, arr0, check0); add_177482_2381377266(params0, LOC73); add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_53)); } goto LA68; LA71: ; { Ropeobj177006* LOC75; LOC75 = (Ropeobj177006*)0; LOC75 = gettypedescaux_531505_839829468(m0, arr0, check0); add_177482_2381377266(params0, LOC75); } LA68: ; memset((void*)LOC76, 0, sizeof(LOC76)); addf_178205_2381377266(params0, ((NimStringDesc*) &T839829468_113), LOC76, 0); } LA62: ; { NIM_BOOL LOC79; LOC79 = (NIM_BOOL)0; LOC79 = ((*t0).callconv == ((Tcallingconvention290002) 8)); if (!(LOC79)) goto LA80; LOC79 = declareenvironment0; LA80: ; if (!LOC79) goto LA81; { if (!!(((*params0) == NIM_NIL))) goto LA85; add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA85: ; add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_114)); } LA81: ; { if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0)) goto LA89; { if (!!(((*params0) == NIM_NIL))) goto LA93; add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA93: ; add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_115)); } LA89: ; { if (!((*params0) == NIM_NIL)) goto LA97; add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_116)); } goto LA95; LA97: ; { add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_117)); } LA95: ; unsureAsgnRef((void**) (&(*params0)), HEX26_177452_2381377266(((NimStringDesc*) &T839829468_118), (*params0))); } N_NIMCALL(Ropeobj177006*, genprocheader_533867_839829468)(Tcgen527027* m0, Tsym290834* prc0) { Ropeobj177006* result0; Ropeobj177006* rettype0; Ropeobj177006* params0; Intset266030 check0; Ropeobj177006* LOC13; result0 = (Ropeobj177006*)0; rettype0 = (Ropeobj177006*)0; params0 = (Ropeobj177006*)0; genclinedir_530813_839829468(&result0, (*prc0).info); { if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 5))&15U)))!=0)) goto LA3; { if (!(((*m0).flags &(1U<<((NU)(((Codegenflag527025) 3))&7U)))!=0)) goto LA7; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_22)); } goto LA5; LA7: ; { add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_23)); } LA5: ; } goto LA1; LA3: ; { if (!((*(*prc0).typ).callconv == ((Tcallingconvention290002) 5))) goto LA11; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_24)); } goto LA1; LA11: ; LA1: ; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_266885_2627731572((&check0)); LOC13 = (Ropeobj177006*)0; LOC13 = manglename_531205_839829468(prc0); fillloc_530282_839829468((&(*prc0).loc), ((Tlockind290808) 7), (*prc0).typ, LOC13, ((Tstorageloc290812) 0)); genprocparams_532115_839829468(m0, (*prc0).typ, &rettype0, &params0, (&check0), NIM_TRUE, NIM_FALSE); { TY533235 LOC18; if (!(*prc0).constraint == 0) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rope_177277_2381377266(Callingconvtostr_531587_839829468[((*(*prc0).typ).callconv)- 0]); LOC18[1] = rettype0; LOC18[2] = (*prc0).loc.r; LOC18[3] = params0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_119), LOC18, 4); } goto LA14; LA16: ; { TY533238 LOC20; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rettype0; LOC20[1] = (*prc0).loc.r; LOC20[2] = params0; result0 = HEX25_177905_2381377266((*(*prc0).constraint).kindU.S3.strval, LOC20, 3); } LA14: ; return result0; } static N_INLINE(Tnode290802*, HEX5BHEX5D_291238_850551059)(Tnode290802* n0, NI i0) { Tnode290802* result0; result0 = (Tnode290802*)0; result0 = (*n0).kindU.S6.sons->data[i0]; return result0; } N_NIMCALL(Tnode290802*, easyresultasgn_558191_839829468)(Tnode290802* n0) { Tnode290802* result0; { result0 = (Tnode290802*)0; switch ((*n0).kind) { case ((Tnodekind290020) 115): case ((Tnodekind290020) 126): { NI i0; i0 = ((NI) 0); { while (1) { NIM_BOOL LOC4; NI LOC5; Tnode290802* LOC7; LOC4 = (NIM_BOOL)0; LOC5 = (NI)0; LOC5 = len_291081_850551059(n0); LOC4 = (i0 < LOC5); if (!(LOC4)) goto LA6; LOC7 = (Tnode290802*)0; LOC7 = HEX5BHEX5D_291238_850551059(n0, i0); LOC4 = ((*LOC7).kind == ((Tnodekind290020) 1) || (*LOC7).kind >= ((Tnodekind290020) 79) && (*LOC7).kind <= ((Tnodekind290020) 81) || (*LOC7).kind == ((Tnodekind290020) 84) || (*LOC7).kind == ((Tnodekind290020) 98) || (*LOC7).kind == ((Tnodekind290020) 101) || (*LOC7).kind == ((Tnodekind290020) 125)); LA6: ; if (!LOC4) goto LA3; i0 += ((NI) 1); } LA3: ; } { NI LOC10; Tnode290802* LOC13; LOC10 = (NI)0; LOC10 = len_291081_850551059(n0); if (!(i0 < LOC10)) goto LA11; LOC13 = (Tnode290802*)0; LOC13 = HEX5BHEX5D_291238_850551059(n0, i0); result0 = easyresultasgn_558191_839829468(LOC13); } LA11: ; } break; case ((Tnodekind290020) 73): case ((Tnodekind290020) 74): { { NIM_BOOL LOC17; Tnode290802* LOC18; Tnode290802* LOC20; LOC17 = (NIM_BOOL)0; LOC18 = (Tnode290802*)0; LOC18 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0)); LOC17 = ((*LOC18).kind == ((Tnodekind290020) 3)); if (!(LOC17)) goto LA19; LOC20 = (Tnode290802*)0; LOC20 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0)); LOC17 = (((Tsymkind290435) 11) == (*(*LOC20).kindU.S4.sym).kind); LA19: ; if (!LOC17) goto LA21; (*n0).flags |= ((NU16)1)<<((((Tnodeflag290427) 14))%(sizeof(NU16)*8)); result0 = HEX5BHEX5D_291238_850551059(n0, ((NI) 1)); goto BeforeRet; } LA21: ; } break; case ((Tnodekind290020) 109): { { NI LOC26; Tnode290802* LOC29; LOC26 = (NI)0; LOC26 = len_291081_850551059(n0); if (!(((NI) 0) < LOC26)) goto LA27; LOC29 = (Tnode290802*)0; LOC29 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0)); result0 = easyresultasgn_558191_839829468(LOC29); { if (!!((result0 == NIM_NIL))) goto LA32; (*n0).flags |= ((NU16)1)<<((((Tnodeflag290427) 14))%(sizeof(NU16)*8)); } LA32: ; } LA27: ; } break; default: { } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj177006*, gettypedesc_533673_839829468)(Tcgen527027* m0, Ttype290840* typ0) { Ropeobj177006* result0; Intset266030 check0; result0 = (Ropeobj177006*)0; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_266885_2627731572((&check0)); result0 = gettypedescaux_531505_839829468(m0, typ0, (&check0)); return result0; } N_NIMCALL(Ropeobj177006*, localvardecl_536532_839829468)(Tcproc527021* p0, Tsym290834* s0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { Ropeobj177006* LOC5; if (!((*s0).loc.k == ((Tlockind290808) 0))) goto LA3; LOC5 = (Ropeobj177006*)0; LOC5 = manglename_531205_839829468(s0); fillloc_530282_839829468((&(*s0).loc), ((Tlockind290808) 2), (*s0).typ, LOC5, ((Tstorageloc290812) 2)); { if (!((*s0).kind == ((Tsymkind290435) 9))) goto LA8; (*s0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 2))%(sizeof(NU16)*8)); } LA8: ; } LA3: ; result0 = gettypedesc_533673_839829468((*p0).module, (*s0).loc.t); { if (!(*s0).constraint == 0) goto LA12; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 8))&31U)))!=0)) goto LA16; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_121)); } LA16: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 7))&31U)))!=0)) goto LA20; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_122)); } LA20: ; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_111)); add_177482_2381377266(&result0, (*s0).loc.r); } goto LA10; LA12: ; { TY530811 LOC23; memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = result0; LOC23[1] = (*s0).loc.r; result0 = HEX25_177905_2381377266((*(*s0).constraint).kindU.S3.strval, LOC23, 2); } LA10: ; return result0; } N_NIMCALL(void, initloc_530273_839829468)(Tloc290816* result0, Tlockind290808 k0, Ttype290840* typ0, Tstorageloc290812 s0) { (*result0).k = k0; (*result0).s = s0; unsureAsgnRef((void**) (&(*result0).t), typ0); unsureAsgnRef((void**) (&(*result0).r), NIM_NIL); (*result0).flags = 0; } N_NIMCALL(void, initlocexprsingleuse_537289_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0) { initloc_530273_839829468(result0, ((Tlockind290808) 0), (*e0).typ, ((Tstorageloc290812) 0)); (*result0).flags |= ((NU16)1)<<((((Tlocflag290810) 8))%(sizeof(NU16)*8)); expr_537248_839829468(p0, e0, result0); } static N_INLINE(Ropeobj177006**, s_527179_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0) { Ropeobj177006** result0; result0 = (Ropeobj177006**)0; result0 = &(*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].sections[(s0)- 0]; return result0; } N_NIMCALL(Ropeobj177006*, indentline_530656_839829468)(Tcproc527021* p0, Ropeobj177006* r0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = r0; { NI i_530680_839829468; NI HEX3Atmp_530683_839829468; NI res_530686_839829468; i_530680_839829468 = (NI)0; HEX3Atmp_530683_839829468 = (NI)0; HEX3Atmp_530683_839829468 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); res_530686_839829468 = ((NI) 0); { while (1) { if (!(res_530686_839829468 <= HEX3Atmp_530683_839829468)) goto LA3; i_530680_839829468 = res_530686_839829468; prepend_177893_2381377266(&result0, indent_530655_839829468); res_530686_839829468 += ((NI) 1); } LA3: ; } } return result0; } N_NIMCALL(void, linefmt_530714_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006** LOC1; Ropeobj177006* LOC2; Ropeobj177006* LOC3; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, args0, args0Len0); LOC3 = (Ropeobj177006*)0; LOC3 = indentline_530656_839829468(p0, LOC2); add_177482_2381377266(LOC1, LOC3); } N_NIMCALL(Ropeobj177006*, rdloc_536188_839829468)(Tloc290816* a0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = (*a0).r; { TY177507 LOC5; if (!(((*a0).flags &(1U<<((NU)(((Tlocflag290810) 0))&15U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = result0; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC5, 1); } LA3: ; return result0; } N_NIMCALL(void, line_530690_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, Ropeobj177006* r0) { Ropeobj177006** LOC1; Ropeobj177006* LOC2; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = indentline_530656_839829468(p0, r0); add_177482_2381377266(LOC1, LOC2); } N_NIMCALL(void, linef_530700_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006** LOC1; Ropeobj177006* LOC2; Ropeobj177006* LOC3; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = HEX25_177905_2381377266(frmt0, args0, args0Len0); LOC3 = (Ropeobj177006*)0; LOC3 = indentline_530656_839829468(p0, LOC2); add_177482_2381377266(LOC1, LOC3); } N_NIMCALL(void, gentypeinfoauxbase_533960_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0, Ropeobj177006* base0) { NI nimtypekind0; Ropeobj177006* size0; TY533235 LOC17; NI flags0; Ropeobj177006* LOC33; TY530811 LOC34; NimStringDesc* LOC35; nimtypekind0 = (NI)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isobjlackingtypefield_531515_839829468(typ0); if (!LOC3) goto LA4; nimtypekind0 = ((NI) 18); } goto LA1; LA4: ; { nimtypekind0 = ((NI) ((*typ0).kind)); } LA1: ; size0 = (Ropeobj177006*)0; { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0)) goto LA9; size0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_133)); } goto LA7; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC12) goto LA13; LOC12 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; size0 = gettypedesc_533673_839829468(m0, origtype0); } goto LA7; LA14: ; { size0 = gettypedesc_533673_839829468(m0, typ0); } LA7: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = name0; LOC17[1] = size0; LOC17[2] = rope_177401_2381377266(((NI64) (nimtypekind0))); LOC17[3] = base0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_134), LOC17, 4); flags0 = ((NI) 0); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = containsgarbagecollectedref_318117_3876443242(typ0); if (!!(LOC20)) goto LA21; flags0 = (NI)(flags0 | ((NI) 1)); } LA21: ; { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = canformacycle_318123_3876443242(typ0); if (!!(LOC25)) goto LA26; flags0 = (NI)(flags0 | ((NI) 2)); } LA26: ; { TY530811 LOC32; if (!!((flags0 == ((NI) 0)))) goto LA30; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = name0; LOC32[1] = rope_177401_2381377266(((NI64) (flags0))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_135), LOC32, 2); } LA30: ; LOC33 = (Ropeobj177006*)0; LOC33 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_129)); memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = name0; LOC35 = (NimStringDesc*)0; LOC35 = typetostring_318017_3876443242(typ0, ((Tprefereddesc318011) 0)); LOC34[1] = rope_177277_2381377266(LOC35); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_136), LOC34, 2); } N_NIMCALL(Ropeobj177006*, getnimnode_533945_839829468)(Tcgen527027* m0) { Ropeobj177006* result0; TY530811 LOC1; result0 = (Ropeobj177006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = (*m0).typenodesname; LOC1[1] = rope_177401_2381377266(((NI64) ((*m0).typenodes))); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_138), LOC1, 2); (*m0).typenodes += ((NI) 1); return result0; } N_NIMCALL(void, gentupleinfo_534551_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) { Ropeobj177006* LOC1; Ropeobj177006* expr0; NI length0; TY530811 LOC15; LOC1 = (Ropeobj177006*)0; LOC1 = rope_177277_2381377266(((NimStringDesc*) &T839829468_18)); gentypeinfoauxbase_533960_839829468(m0, typ0, typ0, name0, LOC1); expr0 = getnimnode_533945_839829468(m0); length0 = sonslen_293327_850551059(typ0); { Ropeobj177006* tmp0; TY530811 LOC6; TY533238 LOC12; if (!(((NI) 0) < length0)) goto LA4; tmp0 = gettempname_531598_839829468(m0); memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = tmp0; LOC6[1] = rope_177401_2381377266(((NI64) (length0))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC6, 2); { NI i_534573_839829468; NI HEX3Atmp_534592_839829468; NI res_534595_839829468; i_534573_839829468 = (NI)0; HEX3Atmp_534592_839829468 = (NI)0; HEX3Atmp_534592_839829468 = (NI)(length0 - ((NI) 1)); res_534595_839829468 = ((NI) 0); { while (1) { Ttype290840* a0; Ropeobj177006* tmp20; TY533238 LOC10; TY533235 LOC11; if (!(res_534595_839829468 <= HEX3Atmp_534592_839829468)) goto LA9; i_534573_839829468 = res_534595_839829468; a0 = (*typ0).sons->data[i_534573_839829468]; tmp20 = getnimnode_533945_839829468(m0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0; LOC10[1] = rope_177401_2381377266(((NI64) (i_534573_839829468))); LOC10[2] = tmp20; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC10, 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = tmp20; LOC11[1] = gettypedesc_533673_839829468(m0, typ0); LOC11[2] = rope_177401_2381377266(((NI64) (i_534573_839829468))); LOC11[3] = gentypeinfo_533941_839829468(m0, a0); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_141), LOC11, 4); res_534595_839829468 += ((NI) 1); } LA9: ; } } memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = expr0; LOC12[1] = rope_177401_2381377266(((NI64) (length0))); LOC12[2] = tmp0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC12, 3); } goto LA2; LA4: ; { TY530811 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = expr0; LOC14[1] = rope_177401_2381377266(((NI64) (length0))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC14, 2); } LA2: ; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = name0; LOC15[1] = expr0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC15, 2); } N_NIMCALL(Ttype290840*, fakeclosuretype_535010_839829468)(Tsym290834* owner0) { Ttype290840* result0; Ttype290840* LOC1; Ttype290840* r0; Ttype290840* LOC2; result0 = (Ttype290840*)0; result0 = newtype_293107_850551059(((Ttypekind290244) 18), owner0); LOC1 = (Ttype290840*)0; LOC1 = newtype_293107_850551059(((Ttypekind290244) 26), owner0); rawaddson_294394_850551059(result0, LOC1); r0 = newtype_293107_850551059(((Ttypekind290244) 22), owner0); LOC2 = (Ttype290840*)0; LOC2 = newtype_293107_850551059(((Ttypekind290244) 18), owner0); rawaddson_294394_850551059(r0, LOC2); rawaddson_294394_850551059(result0, r0); return result0; } N_NIMCALL(void, gentypeinfoaux_534027_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0) { Ropeobj177006* base0; base0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; NI LOC4; Ttype290840* x0; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = sonslen_293327_850551059(typ0); LOC3 = (((NI) 0) < LOC4); if (!(LOC3)) goto LA5; LOC3 = !(((*typ0).sons->data[((NI) 0)] == NIM_NIL)); LA5: ; if (!LOC3) goto LA6; x0 = (*typ0).sons->data[((NI) 0)]; { if (!((*typ0).kind == ((Ttypekind290244) 17))) goto LA10; x0 = skiptypes_294099_850551059(x0, IL64(211106247215360)); } LA10: ; base0 = gentypeinfo_533941_839829468(m0, x0); } goto LA1; LA6: ; { base0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_18)); } LA1: ; gentypeinfoauxbase_533960_839829468(m0, typ0, origtype0, name0, base0); } static N_INLINE(NIM_BOOL, iscomplexvaluetype_536317_839829468)(Ttype290840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC3; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((983056 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); if (LOC1) goto LA2; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind290244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention290002) 8)); LA4: ; LOC1 = LOC3; LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, usestringh_530345_839829468)(Tcgen527027* m0) { { NIM_BOOL LOC5; if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 4))&7U)))!=0))) goto LA3; (*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 4))%(sizeof(NU8)*8)); LOC5 = (NIM_BOOL)0; LOC5 = includestr_147249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_151)); } LA3: ; } N_NIMCALL(Ropeobj177006*, addrloc_536204_839829468)(Tloc290816* a0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = (*a0).r; { NIM_BOOL LOC3; Tctypekind527007 LOC5; Ropeobj177006* LOC8; LOC3 = (NIM_BOOL)0; LOC3 = !((((*a0).flags &(1U<<((NU)(((Tlocflag290810) 0))&15U)))!=0)); if (!(LOC3)) goto LA4; LOC5 = (Tctypekind527007)0; LOC5 = maptype_531394_839829468((*a0).t); LOC3 = !((LOC5 == ((Tctypekind527007) 17))); LA4: ; if (!LOC3) goto LA6; LOC8 = (Ropeobj177006*)0; LOC8 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_128), result0); result0 = HEX26_177447_2381377266(LOC8, ((NimStringDesc*) &T839829468_117)); } LA6: ; return result0; } N_NIMCALL(void, genobjectinit_536242_839829468)(Tcproc527021* p0, Tcprocsection527011 section0, Ttype290840* t0, Tloc290816* a0, NIM_BOOL takeaddr0) { Ttypefieldresult318145 LOC1; LOC1 = (Ttypefieldresult318145)0; LOC1 = analyseobjectwithtypefield_318149_3876443242(t0); switch (LOC1) { case ((Ttypefieldresult318145) 0): { } break; case ((Ttypefieldresult318145) 1): { Ropeobj177006* r0; Ttype290840* s0; TY530811 LOC19; r0 = rdloc_536188_839829468(a0); { TY177507 LOC8; if (!!(takeaddr0)) goto LA6; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = r0; r0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC8, 1); } LA6: ; s0 = skiptypes_294099_850551059(t0, IL64(211106232576256)); { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC11) goto LA12; LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA12: ; if (!!(LOC11)) goto LA13; { while (1) { NIM_BOOL LOC17; LOC17 = (NIM_BOOL)0; LOC17 = ((*s0).kind == ((Ttypekind290244) 17)); if (!(LOC17)) goto LA18; LOC17 = !(((*s0).sons->data[((NI) 0)] == NIM_NIL)); LA18: ; if (!LOC17) goto LA16; add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); s0 = skiptypes_294099_850551059((*s0).sons->data[((NI) 0)], IL64(211106247215360)); } LA16: ; } } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = r0; LOC19[1] = gentypeinfo_533941_839829468((*p0).module, t0); linefmt_530714_839829468(p0, section0, ((NimStringDesc*) &T839829468_154), LOC19, 2); } break; case ((Ttypefieldresult318145) 2): { Ropeobj177006* r0; TY530811 LOC26; { if (!takeaddr0) goto LA23; r0 = addrloc_536204_839829468(a0); } goto LA21; LA23: ; { r0 = rdloc_536188_839829468(a0); } LA21: ; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = r0; LOC26[1] = gentypeinfo_533941_839829468((*p0).module, t0); linefmt_530714_839829468(p0, section0, ((NimStringDesc*) &T839829468_155), LOC26, 2); } break; } } N_NIMCALL(void, constructloc_536388_839829468)(Tcproc527021* p0, Tloc290816* loc0, NIM_BOOL istemp0) { Ttype290840* typ0; typ0 = skiptypes_294099_850551059((*loc0).t, IL64(211106233624832)); { NIM_BOOL LOC3; TY530811 LOC6; LOC3 = (NIM_BOOL)0; LOC3 = iscomplexvaluetype_536317_839829468(typ0); if (!!(LOC3)) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rdloc_536188_839829468(loc0); LOC6[1] = gettypedesc_533673_839829468((*p0).module, typ0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_150), LOC6, 2); } goto LA1; LA4: ; { { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = !(istemp0); if (LOC10) goto LA11; LOC10 = containsgarbagecollectedref_318117_3876443242((*loc0).t); LA11: ; if (!LOC10) goto LA12; { NIM_BOOL LOC16; TY530811 LOC19; LOC16 = (NIM_BOOL)0; LOC16 = isimportedcpptype_531478_839829468(typ0); if (!!(LOC16)) goto LA17; usestringh_530345_839829468((*p0).module); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_536204_839829468(loc0); LOC19[1] = rdloc_536188_839829468(loc0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_152), LOC19, 2); } LA17: ; } LA12: ; genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), (*loc0).t, loc0, NIM_TRUE); } LA1: ; } N_NIMCALL(void, gettemp_535032_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816* result0, NIM_BOOL needsinit0) { Ropeobj177006* LOC1; TY530811 LOC2; (*p0).labels += ((NI) 1); LOC1 = (Ropeobj177006*)0; LOC1 = rope_177401_2381377266(((NI64) ((*p0).labels))); unsureAsgnRef((void**) (&(*result0).r), HEX26_177452_2381377266(((NimStringDesc*) &T839829468_149), LOC1)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC2[1] = (*result0).r; linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_54), LOC2, 2); (*result0).k = ((Tlockind290808) 1); unsureAsgnRef((void**) (&(*result0).t), t0); (*result0).s = ((Tstorageloc290812) 2); (*result0).flags = 0; constructloc_536388_839829468(p0, (&(*result0)), !(needsinit0)); } static N_INLINE(Ropeobj177006*, parentobj_535257_839829468)(Ropeobj177006* accessor0, Tcgen527027* m0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; TY177507 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = accessor0; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_161), LOC7, 1); } goto LA1; LA5: ; { result0 = accessor0; } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, intliteral_537270_839829468)(NI64 i0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (IL64(-2147483648) < i0); if (!(LOC3)) goto LA4; LOC3 = (i0 <= IL64(2147483647)); LA4: ; if (!LOC3) goto LA5; result0 = rope_177401_2381377266(i0); } goto LA1; LA5: ; { TY531289 LOC10; if (!(i0 == IL64(-2147483648))) goto LA8; memset((void*)LOC10, 0, sizeof(LOC10)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_166), LOC10, 0); } goto LA1; LA8: ; { TY177507 LOC14; if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_177401_2381377266(i0); result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC14, 1); } goto LA1; LA12: ; { TY531289 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_168), LOC16, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, int64literal_547430_839829468)(NI64 i0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { TY177507 LOC5; if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_177401_2381377266(i0); result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC5, 1); } goto LA1; LA3: ; { TY531289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_168), LOC7, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, uint64literal_547442_839829468)(NU64 i0) { Ropeobj177006* result0; NimStringDesc* LOC1; NimStringDesc* LOC2; result0 = (Ropeobj177006*)0; LOC1 = (NimStringDesc*)0; LOC2 = (NimStringDesc*)0; LOC2 = HEX24_8401_1689653243(i0); LOC1 = rawNewString(LOC2->Sup.len + 3); appendString(LOC1, LOC2); appendString(LOC1, ((NimStringDesc*) &T839829468_171)); result0 = rope_177277_2381377266(LOC1); return result0; } N_NIMCALL(Ropeobj177006*, getstrlit_547468_839829468)(Tcgen527027* m0, NimStringDesc* s0) { Ropeobj177006* result0; Ropeobj177006* LOC1; TY533238 LOC2; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_79)); result0 = gettempname_531598_839829468(m0); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = result0; LOC2[1] = makecstring_189638_155036129(s0); LOC2[2] = rope_177401_2381377266(((NI64) ((s0 ? s0->Sup.len : 0)))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_177), LOC2, 3); return result0; } N_NIMCALL(Ropeobj177006*, genliteral_547476_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* ty0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { if (!(ty0 == NIM_NIL)) goto LA3; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_165)); } LA3: ; switch ((*n0).kind) { case ((Tnodekind290020) 5) ... ((Tnodekind290020) 15): { Ttype290840* LOC6; LOC6 = (Ttype290840*)0; LOC6 = skiptypes_294099_850551059(ty0, IL64(211106242013440)); switch ((*LOC6).kind) { case ((Ttypekind290244) 2): case ((Ttypekind290244) 5): { result0 = intliteral_537270_839829468((*n0).kindU.S1.intval); } break; case ((Ttypekind290244) 1): { { TY531289 LOC13; if (!!(((*n0).kindU.S1.intval == IL64(0)))) goto LA11; memset((void*)LOC13, 0, sizeof(LOC13)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_169), LOC13, 0); } goto LA9; LA11: ; { TY531289 LOC15; memset((void*)LOC15, 0, sizeof(LOC15)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_170), LOC15, 0); } LA9: ; } break; case ((Ttypekind290244) 35): { result0 = int64literal_547430_839829468((*n0).kindU.S1.intval); } break; case ((Ttypekind290244) 44): { result0 = uint64literal_547442_839829468(((NU64) ((*n0).kindU.S1.intval))); } break; default: { TY530811 LOC19; Ttype290840* LOC20; memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (Ttype290840*)0; LOC20 = skiptypes_294099_850551059(ty0, IL64(211106242013440)); LOC19[0] = gettypedesc_533673_839829468((*p0).module, LOC20); LOC19[1] = intliteral_537270_839829468((*n0).kindU.S1.intval); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_172), LOC19, 2); } break; } } break; case ((Tnodekind290020) 23): { Ttype290840* t0; t0 = skiptypes_294099_850551059(ty0, IL64(211106242013440)); { NIM_BOOL LOC24; NI id0; Ropeobj177006* LOC28; LOC24 = (NIM_BOOL)0; LOC24 = ((*t0).kind == ((Ttypekind290244) 25)); if (!(LOC24)) goto LA25; LOC24 = ((*t0).callconv == ((Tcallingconvention290002) 8)); LA25: ; if (!LOC24) goto LA26; id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC28 = (Ropeobj177006*)0; LOC28 = rope_177401_2381377266(((NI64) (id0))); result0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC28); { TY530811 LOC33; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA31; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC33[1] = result0; addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_173), LOC33, 2); } LA31: ; } goto LA22; LA26: ; { result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_174)); } LA22: ; } break; case ((Tnodekind290020) 20) ... ((Tnodekind290020) 22): { { TY531289 LOC40; if (!(*n0).kindU.S3.strval == 0) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_175), LOC40, 0); } goto LA36; LA38: ; { Ttype290840* LOC42; NI id0; LOC42 = (Ttype290840*)0; LOC42 = skiptypes_294099_850551059(ty0, IL64(211106242013440)); if (!((*LOC42).kind == ((Ttypekind290244) 28))) goto LA43; id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); { TY177507 LOC49; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA47; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = getstrlit_547468_839829468((*p0).module, (*n0).kindU.S3.strval); result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_176), LOC49, 1); } goto LA45; LA47: ; { TY530811 LOC51; memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = (*(*p0).module).tmpbase; LOC51[1] = rope_177401_2381377266(((NI64) (id0))); result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_178), LOC51, 2); } LA45: ; } goto LA36; LA43: ; { result0 = makecstring_189638_155036129((*n0).kindU.S3.strval); } LA36: ; } break; case ((Tnodekind290020) 16) ... ((Tnodekind290020) 18): { NimStringDesc* LOC54; LOC54 = (NimStringDesc*)0; LOC54 = tostrmaxprecision_296007_3471544153((*n0).kindU.S2.floatval); result0 = rope_177277_2381377266(LOC54); } break; default: { NimStringDesc* LOC56; LOC56 = (NimStringDesc*)0; LOC56 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI290020))->Sup.len + 12); appendString(LOC56, ((NimStringDesc*) &T839829468_179)); appendString(LOC56, reprEnum((NI)(*n0).kind, (&NTI290020))); appendChar(LOC56, 41); internalerror_194100_155036129((*n0).info, LOC56); result0 = NIM_NIL; } break; } return result0; } N_NIMCALL(Ropeobj177006*, genliteral_537273_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = genliteral_547476_839829468(p0, n0, (*n0).typ); return result0; } N_NIMCALL(void, gencaserange_535028_839829468)(Tcproc527021* p0, Tnode290802* branch0) { NI length0; length0 = len_291081_850551059(branch0); { NI j_545677_839829468; NI HEX3Atmp_545718_839829468; NI res_545721_839829468; j_545677_839829468 = (NI)0; HEX3Atmp_545718_839829468 = (NI)0; HEX3Atmp_545718_839829468 = (NI)(length0 - ((NI) 2)); res_545721_839829468 = ((NI) 0); { while (1) { if (!(res_545721_839829468 <= HEX3Atmp_545718_839829468)) goto LA3; j_545677_839829468 = res_545721_839829468; { Tnode290802* LOC6; LOC6 = (Tnode290802*)0; LOC6 = HEX5BHEX5D_291238_850551059(branch0, j_545677_839829468); if (!((*LOC6).kind == ((Tnodekind290020) 44))) goto LA7; { TY530811 LOC13; Tnode290802* LOC14; Tnode290802* LOC15; Tnode290802* LOC16; Tnode290802* LOC17; if (!((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 0))&7U)))!=0)) goto LA11; memset((void*)LOC13, 0, sizeof(LOC13)); LOC14 = (Tnode290802*)0; LOC14 = HEX5BHEX5D_291238_850551059(branch0, j_545677_839829468); LOC15 = (Tnode290802*)0; LOC15 = HEX5BHEX5D_291238_850551059(LOC14, ((NI) 0)); LOC13[0] = genliteral_537273_839829468(p0, LOC15); LOC16 = (Tnode290802*)0; LOC16 = HEX5BHEX5D_291238_850551059(branch0, j_545677_839829468); LOC17 = (Tnode290802*)0; LOC17 = HEX5BHEX5D_291238_850551059(LOC16, ((NI) 1)); LOC13[1] = genliteral_537273_839829468(p0, LOC17); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_164), LOC13, 2); } goto LA9; LA11: ; { Tnode290802* v0; Tnode290802* LOC19; Tnode290802* LOC20; LOC19 = (Tnode290802*)0; LOC19 = HEX5BHEX5D_291238_850551059(branch0, j_545677_839829468); LOC20 = (Tnode290802*)0; LOC20 = HEX5BHEX5D_291238_850551059(LOC19, ((NI) 0)); v0 = copynode_294528_850551059(LOC20); { while (1) { Tnode290802* LOC23; Tnode290802* LOC24; TY177507 LOC25; LOC23 = (Tnode290802*)0; LOC23 = HEX5BHEX5D_291238_850551059(branch0, j_545677_839829468); LOC24 = (Tnode290802*)0; LOC24 = HEX5BHEX5D_291238_850551059(LOC23, ((NI) 1)); if (!((*v0).kindU.S1.intval <= (*LOC24).kindU.S1.intval)) goto LA22; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = genliteral_537273_839829468(p0, v0); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_180), LOC25, 1); (*v0).kindU.S1.intval += ((NI) 1); } LA22: ; } } LA9: ; } goto LA4; LA7: ; { TY177507 LOC27; Tnode290802* LOC28; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Tnode290802*)0; LOC28 = HEX5BHEX5D_291238_850551059(branch0, j_545677_839829468); LOC27[0] = genliteral_537273_839829468(p0, LOC28); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_180), LOC27, 1); } LA4: ; res_545721_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, gentraverseproc_535039_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Tnode290802* n0) { { { if (!(n0 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; switch ((*n0).kind) { case ((Tnodekind290020) 138): { { NI i_535068_839829468; NI HEX3Atmp_535239_839829468; NI LOC7; NI res_535242_839829468; i_535068_839829468 = (NI)0; HEX3Atmp_535239_839829468 = (NI)0; LOC7 = (NI)0; LOC7 = sonslen_293351_850551059(n0); HEX3Atmp_535239_839829468 = (NI)(LOC7 - ((NI) 1)); res_535242_839829468 = ((NI) 0); { while (1) { if (!(res_535242_839829468 <= HEX3Atmp_535239_839829468)) goto LA9; i_535068_839829468 = res_535242_839829468; gentraverseproc_535039_839829468(c0, accessor0, (*n0).kindU.S6.sons->data[i_535068_839829468]); res_535242_839829468 += ((NI) 1); } LA9: ; } } } break; case ((Tnodekind290020) 139): { Tcproc527021* p0; Tsym290834* disc0; TY530811 LOC15; TY531289 LOC28; { if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)))) goto LA13; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_162)); } LA13: ; p0 = (*c0).p; disc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = accessor0; LOC15[1] = (*disc0).loc.r; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_163), LOC15, 2); { NI i_535098_839829468; NI HEX3Atmp_535249_839829468; NI LOC17; NI res_535252_839829468; i_535098_839829468 = (NI)0; HEX3Atmp_535249_839829468 = (NI)0; LOC17 = (NI)0; LOC17 = sonslen_293351_850551059(n0); HEX3Atmp_535249_839829468 = (NI)(LOC17 - ((NI) 1)); res_535252_839829468 = ((NI) 1); { while (1) { Tnode290802* branch0; Tnode290802* LOC26; TY531289 LOC27; if (!(res_535252_839829468 <= HEX3Atmp_535249_839829468)) goto LA19; i_535098_839829468 = res_535252_839829468; branch0 = (*n0).kindU.S6.sons->data[i_535098_839829468]; { if (!((*branch0).kind == ((Tnodekind290020) 85))) goto LA22; gencaserange_535028_839829468((*c0).p, branch0); } goto LA20; LA22: ; { TY531289 LOC25; memset((void*)LOC25, 0, sizeof(LOC25)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_181), LOC25, 0); } LA20: ; LOC26 = (Tnode290802*)0; LOC26 = lastson_293364_850551059(branch0); gentraverseproc_535039_839829468(c0, accessor0, LOC26); memset((void*)LOC27, 0, sizeof(LOC27)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_182), LOC27, 0); res_535252_839829468 += ((NI) 1); } LA19: ; } } memset((void*)LOC28, 0, sizeof(LOC28)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_183), LOC28, 0); } break; case ((Tnodekind290020) 3): { Tsym290834* field0; TY530811 LOC34; Ropeobj177006* LOC35; field0 = (*n0).kindU.S4.sym; { if (!((*field0).loc.t == NIM_NIL)) goto LA32; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184)); } LA32: ; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = accessor0; LOC34[1] = (*field0).loc.r; LOC35 = (Ropeobj177006*)0; LOC35 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC34, 2); gentraverseproc_535022_839829468(c0, LOC35, (*field0).loc.t); } break; default: { internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184)); } break; } }BeforeRet: ; } N_NIMCALL(void, linecg_530707_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006** LOC1; Ropeobj177006* LOC2; Ropeobj177006* LOC3; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, args0, args0Len0); LOC3 = (Ropeobj177006*)0; LOC3 = indentline_530656_839829468(p0, LOC2); add_177482_2381377266(LOC1, LOC3); } N_NIMCALL(void, gentraverseproc_535022_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ_535027_839829468) { Ttype290840* typ_535302_839829468; Tcproc527021* p0; { { if (!(typ_535027_839829468 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; typ_535302_839829468 = getuniquetype_526640_2036603609(typ_535027_839829468); p0 = (*c0).p; switch ((*typ_535302_839829468).kind) { case ((Ttypekind290244) 11): case ((Ttypekind290244) 10): case ((Ttypekind290244) 8): { Ttype290840* LOC6; LOC6 = (Ttype290840*)0; LOC6 = lastson_293377_850551059(typ_535302_839829468); gentraverseproc_535022_839829468(c0, accessor0, LOC6); } break; case ((Ttypekind290244) 4): case ((Ttypekind290244) 16): { NI64 arraysize0; Tloc290816 i0; Ttype290840* LOC8; TY530811 LOC9; TY530811 LOC10; Ropeobj177006* LOC11; TY531289 LOC12; arraysize0 = lengthord_318007_3876443242((*typ_535302_839829468).sons->data[((NI) 0)]); memset((void*)(&i0), 0, sizeof(i0)); LOC8 = (Ttype290840*)0; LOC8 = getsystype_336150_3937434831(((Ttypekind290244) 31)); gettemp_535032_839829468(p0, LOC8, (&i0), NIM_FALSE); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = i0.r; LOC9[1] = rope_177401_2381377266(arraysize0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_159), LOC9, 2); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = accessor0; LOC10[1] = i0.r; LOC11 = (Ropeobj177006*)0; LOC11 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC10, 2); gentraverseproc_535022_839829468(c0, LOC11, (*typ_535302_839829468).sons->data[((NI) 1)]); memset((void*)LOC12, 0, sizeof(LOC12)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC12, 0); } break; case ((Ttypekind290244) 17): { { NI i_535325_839829468; NI HEX3Atmp_535384_839829468; NI LOC15; NI res_535387_839829468; i_535325_839829468 = (NI)0; HEX3Atmp_535384_839829468 = (NI)0; LOC15 = (NI)0; LOC15 = sonslen_293327_850551059(typ_535302_839829468); HEX3Atmp_535384_839829468 = (NI)(LOC15 - ((NI) 1)); res_535387_839829468 = ((NI) 0); { while (1) { Ttype290840* x0; Ropeobj177006* LOC22; if (!(res_535387_839829468 <= HEX3Atmp_535384_839829468)) goto LA17; i_535325_839829468 = res_535387_839829468; x0 = (*typ_535302_839829468).sons->data[i_535325_839829468]; { if (!!((x0 == NIM_NIL))) goto LA20; x0 = skiptypes_294099_850551059(x0, IL64(211106247215360)); } LA20: ; LOC22 = (Ropeobj177006*)0; LOC22 = parentobj_535257_839829468(accessor0, (*(*c0).p).module); gentraverseproc_535022_839829468(c0, LOC22, x0); res_535387_839829468 += ((NI) 1); } LA17: ; } } { if (!!(((*typ_535302_839829468).n == NIM_NIL))) goto LA25; gentraverseproc_535039_839829468(c0, accessor0, (*typ_535302_839829468).n); } LA25: ; } break; case ((Ttypekind290244) 18): { Ttype290840* typ0; typ0 = getuniquetype_526640_2036603609(typ_535302_839829468); { NI i_535363_839829468; NI HEX3Atmp_535392_839829468; NI LOC29; NI res_535395_839829468; i_535363_839829468 = (NI)0; HEX3Atmp_535392_839829468 = (NI)0; LOC29 = (NI)0; LOC29 = sonslen_293327_850551059(typ0); HEX3Atmp_535392_839829468 = (NI)(LOC29 - ((NI) 1)); res_535395_839829468 = ((NI) 0); { while (1) { TY530811 LOC32; Ropeobj177006* LOC33; if (!(res_535395_839829468 <= HEX3Atmp_535392_839829468)) goto LA31; i_535363_839829468 = res_535395_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = accessor0; LOC32[1] = rope_177401_2381377266(((NI64) (i_535363_839829468))); LOC33 = (Ropeobj177006*)0; LOC33 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_185), LOC32, 2); gentraverseproc_535022_839829468(c0, LOC33, (*typ0).sons->data[i_535363_839829468]); res_535395_839829468 += ((NI) 1); } LA31: ; } } } break; case ((Ttypekind290244) 22): case ((Ttypekind290244) 28): case ((Ttypekind290244) 24): { TY177507 LOC35; memset((void*)LOC35, 0, sizeof(LOC35)); LOC35[0] = accessor0; linecg_530707_839829468(p0, ((Tcprocsection527011) 2), (*c0).visitorfrmt, LOC35, 1); } break; case ((Ttypekind290244) 25): { { TY177507 LOC41; TY177507 LOC42; if (!((*typ_535302_839829468).callconv == ((Tcallingconvention290002) 8))) goto LA39; memset((void*)LOC41, 0, sizeof(LOC41)); memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = accessor0; LOC41[0] = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_186), LOC42, 1); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), (*c0).visitorfrmt, LOC41, 1); } LA39: ; } break; default: { } break; } }BeforeRet: ; } N_NIMCALL(void, gentraverseprocseq_535399_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ0) { Tcproc527021* p0; Tloc290816 i0; Ttype290840* LOC1; TY533238 LOC2; NimStringDesc* LOC3; TY530811 LOC11; Ropeobj177006* LOC12; TY531289 LOC13; p0 = (*c0).p; memset((void*)(&i0), 0, sizeof(i0)); LOC1 = (Ttype290840*)0; LOC1 = getsystype_336150_3937434831(((Ttypekind290244) 31)); gettemp_535032_839829468(p0, LOC1, (&i0), NIM_FALSE); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = i0.r; LOC2[1] = accessor0; LOC3 = (NimStringDesc*)0; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC6) goto LA7; LOC6 = (((*(*(*(*c0).p).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA7: ; if (!LOC6) goto LA8; LOC3 = copyString(((NimStringDesc*) &T839829468_157)); } goto LA4; LA8: ; { LOC3 = copyString(((NimStringDesc*) &T839829468_158)); } LA4: ; LOC2[2] = rope_177277_2381377266(LOC3); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_156), LOC2, 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = accessor0; LOC11[1] = i0.r; LOC12 = (Ropeobj177006*)0; LOC12 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_187), LOC11, 2); gentraverseproc_535022_839829468(c0, LOC12, (*typ0).sons->data[((NI) 0)]); memset((void*)LOC13, 0, sizeof(LOC13)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC13, 0); } N_NIMCALL(Ropeobj177006*, gentraverseproc_535632_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttypeinforeason535016 reason0) { Ropeobj177006* result0; Ttraversalclosure535019 c0; Tcproc527021* p0; Ropeobj177006* header0; TY177507 LOC3; Ropeobj177006* t0; TY177507 LOC4; TY177507 LOC5; Ropeobj177006* generatedproc0; TY533235 LOC20; Ropeobj177006** LOC21; Ropeobj177006** LOC22; Ropeobj177006** LOC23; TY177507 LOC24; result0 = (Ropeobj177006*)0; memset((void*)(&c0), 0, sizeof(c0)); p0 = newproc_527206_3723162438(NIM_NIL, m0); result0 = gettempname_531598_839829468(m0); switch (reason0) { case ((Ttypeinforeason535016) 0): { c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_145)); } break; default: { } break; } memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = result0; header0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_146), LOC3, 1); t0 = gettypedesc_533673_839829468(m0, typ0); memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = t0; linef_530700_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_147), LOC4, 1); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = t0; linef_530700_839829468(p0, ((Tcprocsection527011) 1), ((NimStringDesc*) &T839829468_148), LOC5, 1); c0.p = p0; { Ropeobj177006* LOC10; if (!((*typ0).kind == ((Ttypekind290244) 24))) goto LA8; LOC10 = (Ropeobj177006*)0; LOC10 = rope_177277_2381377266(((NimStringDesc*) &T839829468_188)); gentraverseprocseq_535399_839829468((&c0), LOC10, typ0); } goto LA6; LA8: ; { { Ttype290840* LOC14; Ropeobj177006* LOC17; LOC14 = (Ttype290840*)0; LOC14 = skiptypes_294099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106232576256)); if (!((65552 &((NU64)1<<((NU)((*LOC14).kind)&63U)))!=0)) goto LA15; LOC17 = (Ropeobj177006*)0; LOC17 = rope_177277_2381377266(((NimStringDesc*) &T839829468_188)); gentraverseproc_535022_839829468((&c0), LOC17, (*typ0).sons->data[((NI) 0)]); } goto LA12; LA15: ; { Ropeobj177006* LOC19; LOC19 = (Ropeobj177006*)0; LOC19 = rope_177277_2381377266(((NimStringDesc*) &T839829468_189)); gentraverseproc_535022_839829468((&c0), LOC19, (*typ0).sons->data[((NI) 0)]); } LA12: ; } LA6: ; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = header0; LOC21 = (Ropeobj177006**)0; LOC21 = s_527179_3723162438(p0, ((Tcprocsection527011) 0)); LOC20[1] = (*LOC21); LOC22 = (Ropeobj177006**)0; LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 1)); LOC20[2] = (*LOC22); LOC23 = (Ropeobj177006**)0; LOC23 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); LOC20[3] = (*LOC23); generatedproc0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_190), LOC20, 4); memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = header0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC24, 1); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], generatedproc0); return result0; } N_NIMCALL(void, genarrayinfo_535005_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) { Ropeobj177006* LOC1; LOC1 = (Ropeobj177006*)0; LOC1 = gentypeinfo_533941_839829468(m0, (*typ0).sons->data[((NI) 1)]); gentypeinfoauxbase_533960_839829468(m0, typ0, typ0, name0, LOC1); } N_NIMCALL(void, gensetinfo_534867_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) { Ropeobj177006* tmp0; TY533238 LOC1; NI64 LOC2; gentypeinfoaux_534027_839829468(m0, typ0, typ0, name0); tmp0 = getnimnode_533945_839829468(m0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = tmp0; LOC2 = (NI64)0; LOC2 = firstord_318001_3876443242(typ0); LOC1[1] = rope_177401_2381377266(LOC2); LOC1[2] = name0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_193), LOC1, 3); } N_NIMCALL(void, genenuminfo_534599_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) { Ropeobj177006* nodeptrs0; NI length0; TY530811 LOC1; Ropeobj177006* enumnames0; Ropeobj177006* specialcases0; NI firstnimnode0; NIM_BOOL hasholes0; Ropeobj177006* enumarray0; Ropeobj177006* counter0; TY177507 LOC24; TY533238 LOC25; TY534847 LOC26; TY533235 LOC27; gentypeinfoaux_534027_839829468(m0, typ0, typ0, name0); nodeptrs0 = gettempname_531598_839829468(m0); length0 = sonslen_293351_850551059((*typ0).n); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = nodeptrs0; LOC1[1] = rope_177401_2381377266(((NI64) (length0))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC1, 2); enumnames0 = (Ropeobj177006*)0; specialcases0 = (Ropeobj177006*)0; firstnimnode0 = (*m0).typenodes; hasholes0 = NIM_FALSE; { NI i_534624_839829468; NI HEX3Atmp_534860_839829468; NI res_534863_839829468; i_534624_839829468 = (NI)0; HEX3Atmp_534860_839829468 = (NI)0; HEX3Atmp_534860_839829468 = (NI)(length0 - ((NI) 1)); res_534863_839829468 = ((NI) 0); { while (1) { Tsym290834* field0; Ropeobj177006* elemnode0; if (!(res_534863_839829468 <= HEX3Atmp_534860_839829468)) goto LA4; i_534624_839829468 = res_534863_839829468; field0 = (*(*(*typ0).n).kindU.S6.sons->data[i_534624_839829468]).kindU.S4.sym; elemnode0 = getnimnode_533945_839829468(m0); { Ropeobj177006* LOC9; if (!((*field0).ast == NIM_NIL)) goto LA7; LOC9 = (Ropeobj177006*)0; LOC9 = makecstring_189638_155036129((*(*field0).name).s); add_177482_2381377266(&enumnames0, LOC9); } goto LA5; LA7: ; { Ropeobj177006* LOC11; LOC11 = (Ropeobj177006*)0; LOC11 = makecstring_189638_155036129((*(*field0).ast).kindU.S3.strval); add_177482_2381377266(&enumnames0, LOC11); } LA5: ; { NimStringDesc* LOC16; if (!(i_534624_839829468 < (NI)(length0 - ((NI) 1)))) goto LA14; LOC16 = (NimStringDesc*)0; LOC16 = rawNewString(tnl_175644_4151366050->Sup.len + 2); appendString(LOC16, ((NimStringDesc*) &T839829468_110)); appendString(LOC16, tnl_175644_4151366050); add_177487_2381377266(&enumnames0, LOC16); } LA14: ; { NIM_BOOL LOC19; TY530811 LOC23; LOC19 = (NIM_BOOL)0; LOC19 = !(((*field0).position == i_534624_839829468)); if (LOC19) goto LA20; LOC19 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 5))&31U)))!=0); LA20: ; if (!LOC19) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = elemnode0; LOC23[1] = rope_177401_2381377266(((NI64) ((*field0).position))); addf_178205_2381377266(&specialcases0, ((NimStringDesc*) &T839829468_194), LOC23, 2); hasholes0 = NIM_TRUE; } LA21: ; res_534863_839829468 += ((NI) 1); } LA4: ; } } enumarray0 = gettempname_531598_839829468(m0); counter0 = gettempname_531598_839829468(m0); memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = counter0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_195), LOC24, 1); memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = enumarray0; LOC25[1] = rope_177401_2381377266(((NI64) (length0))); LOC25[2] = enumnames0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_196), LOC25, 3); memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = counter0; LOC26[1] = rope_177401_2381377266(((NI64) (length0))); LOC26[2] = (*m0).typenodesname; LOC26[3] = rope_177401_2381377266(((NI64) (firstnimnode0))); LOC26[4] = enumarray0; LOC26[5] = nodeptrs0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_197), LOC26, 6); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], specialcases0); memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = getnimnode_533945_839829468(m0); LOC27[1] = rope_177401_2381377266(((NI64) (length0))); LOC27[2] = nodeptrs0; LOC27[3] = name0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_198), LOC27, 4); { TY177507 LOC32; if (!hasholes0) goto LA30; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = name0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_199), LOC32, 1); } LA30: ; } N_NIMCALL(Ropeobj177006*, discriminatortablename_534057_839829468)(Tcgen527027* m0, Ttype290840* objtype_534060_839829468, Tsym290834* d0) { Ropeobj177006* result0; Ttype290840* objtype0; TY530811 LOC8; NimStringDesc* LOC9; result0 = (Ropeobj177006*)0; objtype0 = objtype_534060_839829468; { while (1) { Tsym290834* LOC3; LOC3 = (Tsym290834*)0; LOC3 = lookupinrecord_297119_2984716966((*objtype0).n, (*d0).name); if (!(LOC3 == NIM_NIL)) goto LA2; objtype0 = (*objtype0).sons->data[((NI) 0)]; } LA2: ; } { if (!((*objtype0).sym == NIM_NIL)) goto LA6; internalerror_194100_155036129((*d0).info, ((NimStringDesc*) &T839829468_200)); } LA6: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rope_177401_2381377266(((NI64) ((*objtype0).Sup.id))); LOC9 = (NimStringDesc*)0; LOC9 = mangle_526847_2036603609((*(*d0).name).s); LOC8[1] = rope_177277_2381377266(LOC9); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_201), LOC8, 2); return result0; } N_NIMCALL(void, genobjectfields_534104_839829468)(Tcgen527027* m0, Ttype290840* typ0, Tnode290802* n0, Ropeobj177006* expr0) { switch ((*n0).kind) { case ((Tnodekind290020) 138): { NI L0; L0 = sonslen_293351_850551059(n0); { if (!(L0 == ((NI) 1))) goto LA4; genobjectfields_534104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[((NI) 0)], expr0); } goto LA2; LA4: ; { Ropeobj177006* tmp0; TY530811 LOC9; TY533238 LOC14; if (!(((NI) 0) < L0)) goto LA7; tmp0 = gettempname_531598_839829468(m0); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = tmp0; LOC9[1] = rope_177401_2381377266(((NI64) (L0))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC9, 2); { NI i_534127_839829468; NI HEX3Atmp_534482_839829468; NI res_534485_839829468; i_534127_839829468 = (NI)0; HEX3Atmp_534482_839829468 = (NI)0; HEX3Atmp_534482_839829468 = (NI)(L0 - ((NI) 1)); res_534485_839829468 = ((NI) 0); { while (1) { Ropeobj177006* tmp20; TY533238 LOC13; if (!(res_534485_839829468 <= HEX3Atmp_534482_839829468)) goto LA12; i_534127_839829468 = res_534485_839829468; tmp20 = getnimnode_533945_839829468(m0); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = tmp0; LOC13[1] = rope_177401_2381377266(((NI64) (i_534127_839829468))); LOC13[2] = tmp20; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC13, 3); genobjectfields_534104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[i_534127_839829468], tmp20); res_534485_839829468 += ((NI) 1); } LA12: ; } } memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = expr0; LOC14[1] = rope_177401_2381377266(((NI64) (L0))); LOC14[2] = tmp0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC14, 3); } goto LA2; LA7: ; { TY530811 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = expr0; LOC16[1] = rope_177401_2381377266(((NI64) (L0))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC16, 2); } LA2: ; } break; case ((Tnodekind290020) 139): { Tsym290834* field0; Ropeobj177006* tmp0; NI64 L0; TY534401 LOC18; TY530811 LOC19; field0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; tmp0 = discriminatortablename_534057_839829468(m0, typ0, field0); L0 = lengthord_318007_3876443242((*field0).typ); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = expr0; LOC18[1] = gettypedesc_533673_839829468(m0, typ0); LOC18[2] = (*field0).loc.r; LOC18[3] = gentypeinfo_533941_839829468(m0, (*field0).typ); LOC18[4] = makecstring_189638_155036129((*(*field0).name).s); LOC18[5] = tmp0; LOC18[6] = rope_177401_2381377266(L0); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_202), LOC18, 7); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = tmp0; LOC19[1] = rope_177401_2381377266((NI64)(L0 + IL64(1))); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_203), LOC19, 2); { NI i_534421_839829468; NI HEX3Atmp_534501_839829468; NI LOC21; NI res_534504_839829468; i_534421_839829468 = (NI)0; HEX3Atmp_534501_839829468 = (NI)0; LOC21 = (NI)0; LOC21 = sonslen_293351_850551059(n0); HEX3Atmp_534501_839829468 = (NI)(LOC21 - ((NI) 1)); res_534504_839829468 = ((NI) 1); { while (1) { Tnode290802* b0; Ropeobj177006* tmp20; Tnode290802* LOC24; if (!(res_534504_839829468 <= HEX3Atmp_534501_839829468)) goto LA23; i_534421_839829468 = res_534504_839829468; b0 = (*n0).kindU.S6.sons->data[i_534421_839829468]; tmp20 = getnimnode_533945_839829468(m0); LOC24 = (Tnode290802*)0; LOC24 = lastson_293364_850551059(b0); genobjectfields_534104_839829468(m0, typ0, LOC24, tmp20); switch ((*b0).kind) { case ((Tnodekind290020) 85): { { NI LOC28; LOC28 = (NI)0; LOC28 = sonslen_293351_850551059(b0); if (!(LOC28 < ((NI) 2))) goto LA29; internalerror_194100_155036129((*b0).info, ((NimStringDesc*) &T839829468_204)); } LA29: ; { NI j_534436_839829468; NI HEX3Atmp_534494_839829468; NI LOC32; NI res_534497_839829468; j_534436_839829468 = (NI)0; HEX3Atmp_534494_839829468 = (NI)0; LOC32 = (NI)0; LOC32 = sonslen_293351_850551059(b0); HEX3Atmp_534494_839829468 = (NI)(LOC32 - ((NI) 2)); res_534497_839829468 = ((NI) 0); { while (1) { if (!(res_534497_839829468 <= HEX3Atmp_534494_839829468)) goto LA34; j_534436_839829468 = res_534497_839829468; { NI x0; NI64 LOC39; NI y0; NI64 LOC40; if (!((*(*b0).kindU.S6.sons->data[j_534436_839829468]).kind == ((Tnodekind290020) 44))) goto LA37; LOC39 = (NI64)0; LOC39 = getordvalue_318129_3876443242((*(*b0).kindU.S6.sons->data[j_534436_839829468]).kindU.S6.sons->data[((NI) 0)]); x0 = ((NI) (LOC39)); LOC40 = (NI64)0; LOC40 = getordvalue_318129_3876443242((*(*b0).kindU.S6.sons->data[j_534436_839829468]).kindU.S6.sons->data[((NI) 1)]); y0 = ((NI) (LOC40)); { while (1) { TY533238 LOC43; if (!(x0 <= y0)) goto LA42; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = tmp0; LOC43[1] = rope_177401_2381377266(((NI64) (x0))); LOC43[2] = tmp20; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC43, 3); x0 += ((NI) 1); } LA42: ; } } goto LA35; LA37: ; { TY533238 LOC45; NI64 LOC46; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = tmp0; LOC46 = (NI64)0; LOC46 = getordvalue_318129_3876443242((*b0).kindU.S6.sons->data[j_534436_839829468]); LOC45[1] = rope_177401_2381377266(LOC46); LOC45[2] = tmp20; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC45, 3); } LA35: ; res_534497_839829468 += ((NI) 1); } LA34: ; } } } break; case ((Tnodekind290020) 88): { TY533238 LOC48; memset((void*)LOC48, 0, sizeof(LOC48)); LOC48[0] = tmp0; LOC48[1] = rope_177401_2381377266(L0); LOC48[2] = tmp20; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC48, 3); } break; default: { internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_205)); } break; } res_534504_839829468 += ((NI) 1); } LA23: ; } } } break; case ((Tnodekind290020) 3): { Tsym290834* field0; field0 = (*n0).kindU.S4.sym; { TY534475 LOC55; if (!((*field0).kindU.S4.bitsize == ((NI) 0))) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = expr0; LOC55[1] = gettypedesc_533673_839829468(m0, typ0); LOC55[2] = (*field0).loc.r; LOC55[3] = gentypeinfo_533941_839829468(m0, (*field0).typ); LOC55[4] = makecstring_189638_155036129((*(*field0).name).s); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_206), LOC55, 5); } LA53: ; } break; default: { internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_207)); } break; } } N_NIMCALL(void, genobjectinfo_534508_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0) { Ropeobj177006* tmp0; TY530811 LOC12; Ttype290840* t0; { if (!((*typ0).kind == ((Ttypekind290244) 17))) goto LA3; gentypeinfoaux_534027_839829468(m0, typ0, origtype0, name0); } goto LA1; LA3: ; { Ropeobj177006* LOC6; LOC6 = (Ropeobj177006*)0; LOC6 = rope_177277_2381377266(((NimStringDesc*) &T839829468_18)); gentypeinfoauxbase_533960_839829468(m0, typ0, origtype0, name0, LOC6); } LA1: ; tmp0 = getnimnode_533945_839829468(m0); { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = isimportedcpptype_531478_839829468(typ0); if (!!(LOC9)) goto LA10; genobjectfields_534104_839829468(m0, typ0, (*typ0).n, tmp0); } LA10: ; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = name0; LOC12[1] = tmp0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC12, 2); t0 = (*typ0).sons->data[((NI) 0)]; { while (1) { if (!!((t0 == NIM_NIL))) goto LA14; t0 = skiptypes_294099_850551059(t0, IL64(211106247215360)); (*t0).flags |= ((NU32)1)<<((((Ttypeflag290431) 5))%(sizeof(NU32)*8)); t0 = (*t0).sons->data[((NI) 0)]; } LA14: ; } } N_NIMCALL(void, gendeepcopyproc_536066_839829468)(Tcgen527027* m0, Tsym290834* s0, Ropeobj177006* result0) { TY530811 LOC1; genproc_530951_839829468(m0, s0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = result0; LOC1[1] = (*s0).loc.r; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_208), LOC1, 2); } N_NIMCALL(Ropeobj177006*, gentypeinfo_533941_839829468)(Tcgen527027* m0, Ttype290840* t_533944_839829468) { Ropeobj177006* result0; Ttype290840* origtype0; Ttype290840* t0; TY177507 LOC1; Tsym290834* owner0; Ttype290840* LOC12; Ropeobj177006* LOC66; Ropeobj177006* LOC67; Ropeobj177006* LOC68; { result0 = (Ropeobj177006*)0; origtype0 = t_533944_839829468; t0 = getuniquetype_526640_2036603609(t_533944_839829468); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rope_177401_2381377266(((NI64) ((*t0).Sup.id))); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_127), LOC1, 1); { NIM_BOOL LOC4; Ropeobj177006* LOC7; Ropeobj177006* LOC8; Ropeobj177006* LOC9; LOC4 = (NIM_BOOL)0; LOC4 = containsorincl_266862_2627731572((&(*m0).typeinfomarker), (*t0).Sup.id); if (!LOC4) goto LA5; LOC7 = (Ropeobj177006*)0; LOC7 = rope_177277_2381377266(((NimStringDesc*) &T839829468_128)); LOC8 = (Ropeobj177006*)0; LOC8 = HEX26_177418_2381377266(LOC7, result0); LOC9 = (Ropeobj177006*)0; LOC9 = rope_177277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_177418_2381377266(LOC8, LOC9); goto BeforeRet; } LA5: ; { while (1) { if (!((*t0).kind == ((Ttypekind290244) 13))) goto LA11; t0 = lastson_293377_850551059(t0); } LA11: ; } LOC12 = (Ttype290840*)0; LOC12 = skiptypes_294099_850551059(t0, IL64(211106247256320)); owner0 = getmodule_297123_2984716966((*LOC12).owner); { Tcgen527027* LOC17; Ropeobj177006* LOC18; Ropeobj177006* LOC19; Ropeobj177006* LOC20; TY530811 LOC21; NimStringDesc* LOC22; Ropeobj177006* LOC23; Ropeobj177006* LOC24; Ropeobj177006* LOC25; if (!!((owner0 == (*m0).module))) goto LA15; LOC17 = (Tcgen527027*)0; LOC17 = bmod_527201_3723162438(owner0); LOC18 = (Ropeobj177006*)0; LOC18 = gentypeinfo_533941_839829468(LOC17, t0); LOC19 = (Ropeobj177006*)0; LOC19 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_129)); LOC20 = (Ropeobj177006*)0; LOC20 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_130)); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = result0; LOC22 = (NimStringDesc*)0; LOC22 = typetostring_318017_3876443242(t0, ((Tprefereddesc318011) 0)); LOC21[1] = rope_177277_2381377266(LOC22); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_131), LOC21, 2); LOC23 = (Ropeobj177006*)0; LOC23 = rope_177277_2381377266(((NimStringDesc*) &T839829468_128)); LOC24 = (Ropeobj177006*)0; LOC24 = HEX26_177418_2381377266(LOC23, result0); LOC25 = (Ropeobj177006*)0; LOC25 = rope_177277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_177418_2381377266(LOC24, LOC25); goto BeforeRet; } LA15: ; switch ((*t0).kind) { case ((Ttypekind290244) 3): case ((Ttypekind290244) 62): { result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_132)); } break; case ((Ttypekind290244) 26): case ((Ttypekind290244) 1): case ((Ttypekind290244) 2): case ((Ttypekind290244) 29): case ((Ttypekind290244) 28): case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44): case ((Ttypekind290244) 23): { Ropeobj177006* LOC28; LOC28 = (Ropeobj177006*)0; LOC28 = rope_177277_2381377266(((NimStringDesc*) &T839829468_132)); gentypeinfoauxbase_533960_839829468(m0, t0, t0, result0, LOC28); } break; case ((Ttypekind290244) 59): { { Ttype290840* LOC34; if (!!(((*t0).n == NIM_NIL))) goto LA32; LOC34 = (Ttype290840*)0; LOC34 = lastson_293377_850551059(t0); result0 = gentypeinfo_533941_839829468(m0, LOC34); } goto LA30; LA32: ; { NimStringDesc* LOC36; LOC36 = (NimStringDesc*)0; LOC36 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI290244))->Sup.len + 13); appendString(LOC36, ((NimStringDesc*) &T839829468_137)); appendString(LOC36, reprEnum((NI)(*t0).kind, (&NTI290244))); appendChar(LOC36, 41); internalerror_194113_155036129(LOC36); } LA30: ; } break; case ((Ttypekind290244) 25): { { Ropeobj177006* LOC42; if (!!(((*t0).callconv == ((Tcallingconvention290002) 8)))) goto LA40; LOC42 = (Ropeobj177006*)0; LOC42 = rope_177277_2381377266(((NimStringDesc*) &T839829468_132)); gentypeinfoauxbase_533960_839829468(m0, t0, t0, result0, LOC42); } goto LA38; LA40: ; { Ttype290840* LOC44; LOC44 = (Ttype290840*)0; LOC44 = fakeclosuretype_535010_839829468((*t0).owner); gentupleinfo_534551_839829468(m0, LOC44, result0); } LA38: ; } break; case ((Ttypekind290244) 24): case ((Ttypekind290244) 22): { gentypeinfoaux_534027_839829468(m0, t0, t0, result0); { Ropeobj177006* markerproc0; TY530811 LOC50; if (!(((Tgcmode168080) 4) <= gselectedgc_168133_2607990831)) goto LA48; markerproc0 = gentraverseproc_535632_839829468(m0, t0, ((Ttypeinforeason535016) 0)); memset((void*)LOC50, 0, sizeof(LOC50)); LOC50[0] = result0; LOC50[1] = markerproc0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_192), LOC50, 2); } LA48: ; } break; case ((Ttypekind290244) 21): case ((Ttypekind290244) 20): { gentypeinfoaux_534027_839829468(m0, t0, t0, result0); } break; case ((Ttypekind290244) 4): case ((Ttypekind290244) 16): { genarrayinfo_535005_839829468(m0, t0, result0); } break; case ((Ttypekind290244) 19): { gensetinfo_534867_839829468(m0, t0, result0); } break; case ((Ttypekind290244) 14): { genenuminfo_534599_839829468(m0, t0, result0); } break; case ((Ttypekind290244) 17): { genobjectinfo_534508_839829468(m0, t0, origtype0, result0); } break; case ((Ttypekind290244) 18): { gentupleinfo_534551_839829468(m0, t0, result0); } break; default: { NimStringDesc* LOC58; LOC58 = (NimStringDesc*)0; LOC58 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI290244))->Sup.len + 13); appendString(LOC58, ((NimStringDesc*) &T839829468_137)); appendString(LOC58, reprEnum((NI)(*t0).kind, (&NTI290244))); appendChar(LOC58, 41); internalerror_194113_155036129(LOC58); } break; } { if (!!(((*t0).deepcopy == NIM_NIL))) goto LA61; gendeepcopyproc_536066_839829468(m0, (*t0).deepcopy, result0); } goto LA59; LA61: ; { if (!!(((*origtype0).deepcopy == NIM_NIL))) goto LA64; gendeepcopyproc_536066_839829468(m0, (*origtype0).deepcopy, result0); } goto LA59; LA64: ; LA59: ; LOC66 = (Ropeobj177006*)0; LOC66 = rope_177277_2381377266(((NimStringDesc*) &T839829468_128)); LOC67 = (Ropeobj177006*)0; LOC67 = HEX26_177418_2381377266(LOC66, result0); LOC68 = (Ropeobj177006*)0; LOC68 = rope_177277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_177418_2381377266(LOC67, LOC68); }BeforeRet: ; return result0; } N_NIMCALL(void, localdebuginfo_536449_839829468)(Tcproc527021* p0, Tsym290834* s0) { Ropeobj177006* a0; TY533235 LOC16; NimStringDesc* LOC17; { { if (!!(((163840 & (*p0).options) == 163840))) goto LA3; goto BeforeRet; } LA3: ; { Ttype290840* LOC7; LOC7 = (Ttype290840*)0; LOC7 = skiptypes_294099_850551059((*s0).typ, IL64(211106240964864)); if (!((IL64(281475110928384) &((NU64)1<<((NU)((*LOC7).kind)&63U)))!=0)) goto LA8; goto BeforeRet; } LA8: ; a0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_52), (*s0).loc.r); { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*s0).kind == ((Tsymkind290435) 3)); if (!(LOC12)) goto LA13; LOC12 = ccgintroducedptr_531611_839829468(s0); LA13: ; if (!LOC12) goto LA14; a0 = (*s0).loc.r; } LA14: ; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rope_177401_2381377266(((NI64) ((*p0).maxframelen))); LOC17 = (NimStringDesc*)0; LOC17 = nsuNormalize((*(*s0).name).s); LOC16[1] = makecstring_189638_155036129(LOC17); LOC16[2] = a0; LOC16[3] = gentypeinfo_533941_839829468((*p0).module, (*s0).loc.t); linef_530700_839829468(p0, ((Tcprocsection527011) 1), ((NimStringDesc*) &T839829468_126), LOC16, 4); (*p0).maxframelen += ((NI) 1); (*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].framelen += ((NI) 1); }BeforeRet: ; } N_NIMCALL(void, assignlocalvar_536614_839829468)(Tcproc527021* p0, Tsym290834* s0) { Ropeobj177006* decl0; Ropeobj177006* LOC1; Ropeobj177006* LOC2; LOC1 = (Ropeobj177006*)0; LOC1 = localvardecl_536532_839829468(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = HEX26_177447_2381377266(LOC1, ((NimStringDesc*) &T839829468_125)); decl0 = HEX26_177447_2381377266(LOC2, tnl_175644_4151366050); line_530690_839829468(p0, ((Tcprocsection527011) 0), decl0); localdebuginfo_536449_839829468(p0, s0); } N_NIMCALL(void, initlocalvar_536398_839829468)(Tcproc527021* p0, Tsym290834* v0, NIM_BOOL immediateasgn0) { { if (!!((((*v0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0))) goto LA3; { if (!!(immediateasgn0)) goto LA7; constructloc_536388_839829468(p0, (&(*v0).loc), NIM_FALSE); } LA7: ; } LA3: ; } N_NIMCALL(void, fillresult_531865_839829468)(Tsym290834* param0) { TY531289 LOC1; Ropeobj177006* LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (Ropeobj177006*)0; LOC2 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_210), LOC1, 0); fillloc_530282_839829468((&(*param0).loc), ((Tlockind290808) 4), (*param0).typ, LOC2, ((Tstorageloc290812) 2)); { NIM_BOOL LOC5; Tctypekind527007 LOC6; LOC5 = (NIM_BOOL)0; LOC6 = (Tctypekind527007)0; LOC6 = mapreturntype_531447_839829468((*param0).typ); LOC5 = !((LOC6 == ((Tctypekind527007) 17))); if (!(LOC5)) goto LA7; LOC5 = isinvalidreturntype_531550_839829468((*param0).typ); LA7: ; if (!LOC5) goto LA8; (*param0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 0))%(sizeof(NU16)*8)); (*param0).loc.s = ((Tstorageloc290812) 0); } LA8: ; } N_NIMCALL(void, assignparam_536994_839829468)(Tcproc527021* p0, Tsym290834* s0) { localdebuginfo_536449_839829468(p0, s0); } N_NIMCALL(void, closuresetup_558158_839829468)(Tcproc527021* p0, Tsym290834* prc0) { Tnode290802* ls0; Tnode290802* LOC5; Tsym290834* env0; TY530811 LOC10; { { if (!!((((*(*prc0).typ).flags &(1U<<((NU)(((Ttypeflag290431) 11))&31U)))!=0))) goto LA3; goto BeforeRet; } LA3: ; LOC5 = (Tnode290802*)0; LOC5 = HEX5BHEX5D_291238_850551059((*prc0).ast, ((NI) 3)); ls0 = lastson_293364_850551059(LOC5); { if (!!(((*ls0).kind == ((Tnodekind290020) 3)))) goto LA8; internalerror_194100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_211)); } LA8: ; env0 = (*ls0).kindU.S4.sym; assignlocalvar_536614_839829468(p0, env0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_536188_839829468((&(*env0).loc)); LOC10[1] = gettypedesc_533673_839829468((*p0).module, (*env0).typ); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_212), LOC10, 2); }BeforeRet: ; } N_NIMCALL(Ropeobj177006*, initgcframe_536435_839829468)(Tcproc527021* p0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { TY177507 LOC5; if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = (*p0).gcframetype; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_217), LOC5, 1); } LA3: ; return result0; } N_NIMCALL(Ropeobj177006*, initframe_558140_839829468)(Tcproc527021* p0, Ropeobj177006* procname0, Ropeobj177006* filename0) { Ropeobj177006* result0; Ropeobj177006* LOC1; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_218)); { Ropeobj177006* LOC6; TY533235 LOC7; if (!(((NI) 0) < (*p0).maxframelen)) goto LA4; LOC6 = (Ropeobj177006*)0; LOC6 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_219)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = procname0; LOC7[1] = filename0; LOC7[2] = rope_177401_2381377266(((NI64) ((*p0).maxframelen))); LOC7[3] = rope_177401_2381377266(((NI64) ((*p0).blocks->data[((NI) 0)].framelen))); result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_220), LOC7, 4); } goto LA2; LA4: ; { TY530811 LOC9; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = procname0; LOC9[1] = filename0; result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_221), LOC9, 2); } LA2: ; return result0; } N_NIMCALL(void, appcg_530648_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006** LOC1; Ropeobj177006* LOC2; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, args0, args0Len0); add_177482_2381377266(LOC1, LOC2); } N_NIMCALL(Ropeobj177006*, deinitgcframe_536441_839829468)(Tcproc527021* p0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { TY531289 LOC5; if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_225), LOC5, 0); } LA3: ; return result0; } N_NIMCALL(Ropeobj177006*, deinitframe_558150_839829468)(Tcproc527021* p0) { Ropeobj177006* result0; TY531289 LOC1; result0 = (Ropeobj177006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_226), LOC1, 0); return result0; } N_NIMCALL(void, genprocaux_558284_839829468)(Tcgen527027* m0, Tsym290834* prc0) { Tcproc527021* p0; Ropeobj177006* header0; Ropeobj177006* returnstmt0; Tnode290802* LOC51; Ropeobj177006* generatedproc0; p0 = newproc_527206_3723162438(prc0, m0); header0 = genprocheader_533867_839829468(m0, prc0); returnstmt0 = NIM_NIL; { NIM_BOOL LOC3; Tsym290834* res0; LOC3 = (NIM_BOOL)0; LOC3 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)); if (!(LOC3)) goto LA4; LOC3 = !(((*(*prc0).typ).sons->data[((NI) 0)] == NIM_NIL)); LA4: ; if (!LOC3) goto LA5; { NI LOC9; LOC9 = (NI)0; LOC9 = len_291081_850551059((*prc0).ast); if (!(LOC9 <= ((NI) 7))) goto LA10; internalerror_194100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_120)); } LA10: ; res0 = (*(*(*prc0).ast).kindU.S6.sons->data[((NI) 7)]).kindU.S4.sym; { NIM_BOOL LOC14; TY177507 LOC34; LOC14 = (NIM_BOOL)0; LOC14 = isinvalidreturntype_531550_839829468((*(*prc0).typ).sons->data[((NI) 0)]); if (!!(LOC14)) goto LA15; { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA19; (*res0).flags |= ((NU32)1)<<((((Tsymflag290184) 12))%(sizeof(NU32)*8)); } LA19: ; { NIM_BOOL LOC23; NIM_BOOL LOC24; NIM_BOOL LOC26; Tnode290802* val0; Tnode290802* LOC29; Ropeobj177006* decl0; Tloc290816 a0; TY530811 LOC32; LOC23 = (NIM_BOOL)0; LOC24 = (NIM_BOOL)0; LOC24 = (((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0); if (!(LOC24)) goto LA25; LOC26 = (NIM_BOOL)0; LOC26 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC26) goto LA27; LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA27: ; LOC24 = LOC26; LA25: ; LOC23 = LOC24; if (!(LOC23)) goto LA28; LOC29 = (Tnode290802*)0; LOC29 = getbody_333226_1724185294(prc0); val0 = easyresultasgn_558191_839829468(LOC29); LOC23 = !((val0 == NIM_NIL)); LA28: ; if (!LOC23) goto LA30; decl0 = localvardecl_536532_839829468(p0, res0); memset((void*)(&a0), 0, sizeof(a0)); initlocexprsingleuse_537289_839829468(p0, val0, (&a0)); memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = decl0; LOC32[1] = rdloc_536188_839829468((&a0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC32, 2); } goto LA21; LA30: ; { assignlocalvar_536614_839829468(p0, res0); initlocalvar_536398_839829468(p0, res0, NIM_FALSE); } LA21: ; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = rdloc_536188_839829468((&(*res0).loc)); returnstmt0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_209), LOC34, 1); } goto LA12; LA15: ; { fillresult_531865_839829468(res0); assignparam_536994_839829468(p0, res0); { Ttype290840* LOC38; LOC38 = (Ttype290840*)0; LOC38 = skiptypes_294099_850551059((*res0).typ, IL64(211106232576256)); if (!((*LOC38).kind == ((Ttypekind290244) 16))) goto LA39; (*res0).loc.s = ((Tstorageloc290812) 0); } LA39: ; } LA12: ; } LA5: ; { NI i_558627_839829468; NI HEX3Atmp_558743_839829468; NI LOC42; NI res_558746_839829468; i_558627_839829468 = (NI)0; HEX3Atmp_558743_839829468 = (NI)0; LOC42 = (NI)0; LOC42 = sonslen_293351_850551059((*(*prc0).typ).n); HEX3Atmp_558743_839829468 = (NI)(LOC42 - ((NI) 1)); res_558746_839829468 = ((NI) 1); { while (1) { if (!(res_558746_839829468 <= HEX3Atmp_558743_839829468)) goto LA44; i_558627_839829468 = res_558746_839829468; { Tsym290834* param0; param0 = (*(*(*(*prc0).typ).n).kindU.S6.sons->data[i_558627_839829468]).kindU.S4.sym; { NIM_BOOL LOC48; LOC48 = (NIM_BOOL)0; LOC48 = iscompiletimeonly_326706_3876443242((*param0).typ); if (!LOC48) goto LA49; goto LA45; } LA49: ; assignparam_536994_839829468(p0, param0); } LA45: ; res_558746_839829468 += ((NI) 1); } LA44: ; } } closuresetup_558158_839829468(p0, prc0); LOC51 = (Tnode290802*)0; LOC51 = getbody_333226_1724185294(prc0); genstmts_537244_839829468(p0, LOC51); generatedproc0 = (Ropeobj177006*)0; { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 14))&31U)))!=0)) goto LA54; { if (!((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 6))&7U)))!=0)) goto LA58; header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_213), header0); } LA58: ; } LA54: ; { TY533235 LOC68; Ropeobj177006** LOC69; Ropeobj177006** LOC70; Ropeobj177006** LOC71; if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)) goto LA62; { if (!((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 6))&7U)))!=0)) goto LA66; header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_214), header0); } LA66: ; memset((void*)LOC68, 0, sizeof(LOC68)); LOC68[0] = header0; LOC69 = (Ropeobj177006**)0; LOC69 = s_527179_3723162438(p0, ((Tcprocsection527011) 0)); LOC68[1] = (*LOC69); LOC70 = (Ropeobj177006**)0; LOC70 = s_527179_3723162438(p0, ((Tcprocsection527011) 1)); LOC68[2] = (*LOC70); LOC71 = (Ropeobj177006**)0; LOC71 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); LOC68[3] = (*LOC71); generatedproc0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_215), LOC68, 4); } goto LA60; LA62: ; { TY177507 LOC73; Ropeobj177006* LOC74; Ropeobj177006** LOC93; Ropeobj177006** LOC94; Ropeobj177006* LOC101; TY531289 LOC107; Ropeobj177006* LOC108; memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = header0; generatedproc0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_216), LOC73, 1); LOC74 = (Ropeobj177006*)0; LOC74 = initgcframe_536435_839829468(p0); add_177482_2381377266(&generatedproc0, LOC74); { Ropeobj177006** LOC79; Ropeobj177006* procname0; Ropeobj177006* LOC80; Ropeobj177006* LOC81; if (!(((*prc0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA77; LOC79 = (Ropeobj177006**)0; LOC79 = s_527179_3723162438(p0, ((Tcprocsection527011) 0)); add_177482_2381377266(&generatedproc0, (*LOC79)); procname0 = makecstring_189638_155036129((*(*prc0).name).s); LOC80 = (Ropeobj177006*)0; LOC80 = quotedfilename_194818_155036129((*prc0).info); LOC81 = (Ropeobj177006*)0; LOC81 = initframe_558140_839829468(p0, procname0, LOC80); add_177482_2381377266(&generatedproc0, LOC81); } goto LA75; LA77: ; { Ropeobj177006** LOC83; LOC83 = (Ropeobj177006**)0; LOC83 = s_527179_3723162438(p0, ((Tcprocsection527011) 0)); add_177482_2381377266(&generatedproc0, (*LOC83)); } LA75: ; { TY531289 LOC88; if (!(((*prc0).options &(1U<<((NU)(((Toption168009) 19))&31U)))!=0)) goto LA86; memset((void*)LOC88, 0, sizeof(LOC88)); appcg_530648_839829468(p0, ((Tcprocsection527011) 1), ((NimStringDesc*) &T839829468_222), LOC88, 0); } LA86: ; { if (!(*p0).beforeretneeded) goto LA91; add_177487_2381377266(&generatedproc0, ((NimStringDesc*) &T839829468_223)); } LA91: ; LOC93 = (Ropeobj177006**)0; LOC93 = s_527179_3723162438(p0, ((Tcprocsection527011) 1)); add_177482_2381377266(&generatedproc0, (*LOC93)); LOC94 = (Ropeobj177006**)0; LOC94 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(&generatedproc0, (*LOC94)); { TY531289 LOC99; Ropeobj177006* LOC100; if (!(*p0).beforeretneeded) goto LA97; memset((void*)LOC99, 0, sizeof(LOC99)); LOC100 = (Ropeobj177006*)0; LOC100 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_224), LOC99, 0); add_177482_2381377266(&generatedproc0, LOC100); } LA97: ; LOC101 = (Ropeobj177006*)0; LOC101 = deinitgcframe_536441_839829468(p0); add_177482_2381377266(&generatedproc0, LOC101); { Ropeobj177006* LOC106; if (!(((*prc0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA104; LOC106 = (Ropeobj177006*)0; LOC106 = deinitframe_558150_839829468(p0); add_177482_2381377266(&generatedproc0, LOC106); } LA104: ; add_177482_2381377266(&generatedproc0, returnstmt0); memset((void*)LOC107, 0, sizeof(LOC107)); LOC108 = (Ropeobj177006*)0; LOC108 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_227), LOC107, 0); add_177482_2381377266(&generatedproc0, LOC108); } LA60: ; add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], generatedproc0); } N_NIMCALL(Tcgen527027*, findpendingmodule_530241_839829468)(Tcgen527027* m0, Tsym290834* s0) { Tcgen527027* result0; Tsym290834* ms0; result0 = (Tcgen527027*)0; ms0 = getmodule_297123_2984716966(s0); result0 = gmodules_527170_3723162438->data[(*ms0).position]; return result0; } N_NIMCALL(NIM_BOOL, isgetprocaddr_557443_839829468)(Tlib290820* lib0) { NIM_BOOL result0; Tnode290802* n0; NIM_BOOL LOC1; NIM_BOOL LOC2; result0 = (NIM_BOOL)0; n0 = (*lib0).path; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = ((*n0).kind == ((Tnodekind290020) 27) || (*n0).kind == ((Tnodekind290020) 29) || (*n0).kind == ((Tnodekind290020) 30) || (*n0).kind == ((Tnodekind290020) 31) || (*n0).kind == ((Tnodekind290020) 26) || (*n0).kind == ((Tnodekind290020) 28) || (*n0).kind == ((Tnodekind290020) 32)); if (!(LOC2)) goto LA3; LOC2 = !(((*n0).typ == NIM_NIL)); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA4; LOC1 = ((100663296 &((NU64)1<<((NU)((*(*n0).typ).kind)&63U)))!=0); LA4: ; result0 = LOC1; return result0; } N_NIMCALL(void, initlocexpr_537283_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0) { initloc_530273_839829468(result0, ((Tlockind290808) 0), (*e0).typ, ((Tstorageloc290812) 0)); expr_537248_839829468(p0, e0, result0); } N_NIMCALL(void, loaddynamiclib_557481_839829468)(Tcgen527027* m0, Tlib290820* lib0) { { Ropeobj177006* tmp0; TY177507 LOC5; if (!!((*lib0).generated)) goto LA3; (*lib0).generated = NIM_TRUE; tmp0 = gettempname_531598_839829468(m0); asgnRefNoCycle((void**) (&(*lib0).name), tmp0); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = tmp0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_228), LOC5, 1); { TY134602* s0; Ropeobj177006* loadlib0; TY530811 LOC18; if (!((*(*lib0).path).kind >= ((Tnodekind290020) 20) && (*(*lib0).path).kind <= ((Tnodekind290020) 22))) goto LA8; s0 = (TY134602*) newSeq((&NTI134602), 0); libcandidates_169605_2607990831((*(*lib0).path).kindU.S3.strval, (&s0)); rawmessage_192612_155036129(((Tmsgkind189002) 286), (*(*lib0).path).kindU.S3.strval); loadlib0 = NIM_NIL; { NI i_557847_839829468; NI HEX3Atmp_557902_839829468; NI res_557905_839829468; i_557847_839829468 = (NI)0; HEX3Atmp_557902_839829468 = (NI)0; HEX3Atmp_557902_839829468 = (s0 ? (s0->Sup.len-1) : -1); res_557905_839829468 = ((NI) 0); { while (1) { TY530811 LOC17; if (!(res_557905_839829468 <= HEX3Atmp_557902_839829468)) goto LA12; i_557847_839829468 = res_557905_839829468; (*m0).labels += ((NI) 1); { if (!(((NI) 0) < i_557847_839829468)) goto LA15; add_177487_2381377266(&loadlib0, ((NimStringDesc*) &T839829468_229)); } LA15: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = tmp0; LOC17[1] = getstrlit_547468_839829468(m0, s0->data[i_557847_839829468]); appcg_530632_839829468(m0, &loadlib0, ((NimStringDesc*) &T839829468_230), LOC17, 2); res_557905_839829468 += ((NI) 1); } LA12: ; } } memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = loadlib0; LOC18[1] = getstrlit_547468_839829468(m0, (*(*lib0).path).kindU.S3.strval); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_231), LOC18, 2); } goto LA6; LA8: ; { Tcproc527021* p0; Tloc290816 dest0; Ropeobj177006** LOC20; Ropeobj177006** LOC21; Ropeobj177006** LOC22; TY530811 LOC23; p0 = newproc_527206_3723162438(NIM_NIL, m0); (*p0).options = ((*p0).options & ~ 163840); memset((void*)(&dest0), 0, sizeof(dest0)); initlocexpr_537283_839829468(p0, (*lib0).path, (&dest0)); LOC20 = (Ropeobj177006**)0; LOC20 = s_527179_3723162438(p0, ((Tcprocsection527011) 0)); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], (*LOC20)); LOC21 = (Ropeobj177006**)0; LOC21 = s_527179_3723162438(p0, ((Tcprocsection527011) 1)); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 16))- 0], (*LOC21)); LOC22 = (Ropeobj177006**)0; LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 16))- 0], (*LOC22)); memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = tmp0; LOC23[1] = rdloc_536188_839829468((&dest0)); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_232), LOC23, 2); } LA6: ; } LA3: ; { if (!((*lib0).name == NIM_NIL)) goto LA26; internalerror_194113_155036129(((NimStringDesc*) &T839829468_233)); } LA26: ; } N_NIMCALL(Ropeobj177006*, mangledynlibproc_536816_839829468)(Tsym290834* sym0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 16))&31U)))!=0)) goto LA3; result0 = rope_177277_2381377266((*(*sym0).name).s); } goto LA1; LA3: ; { TY177507 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_177401_2381377266(((NI64) ((*sym0).Sup.id))); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_234), LOC6, 1); } LA1: ; return result0; } N_NIMCALL(void, symindynamiclib_557929_839829468)(Tcgen527027* m0, Tsym290834* sym0) { Tlib290820* lib0; NIM_BOOL iscall0; Ropeobj177006* extname0; Ropeobj177006* tmp0; TY530811 LOC43; lib0 = (*sym0).annex; iscall0 = isgetprocaddr_557443_839829468(lib0); extname0 = (*sym0).loc.r; { if (!!(iscall0)) goto LA3; loaddynamiclib_557481_839829468(m0, lib0); } LA3: ; tmp0 = mangledynlibproc_536816_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0); asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL); (*m0).labels += ((NI) 2); { Tnode290802* n0; Tloc290816 a0; Tnode290802* LOC9; Ropeobj177006* params0; Ropeobj177006* LOC10; Ropeobj177006* load0; TY533235 LOC17; NimStringDesc* LOC18; Tnode290802* last0; NimStringDesc* idx0; if (!iscall0) goto LA7; n0 = (*lib0).path; memset((void*)(&a0), 0, sizeof(a0)); LOC9 = (Tnode290802*)0; LOC9 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0)); initlocexpr_537283_839829468((*m0).initproc, LOC9, (&a0)); LOC10 = (Ropeobj177006*)0; LOC10 = rdloc_536188_839829468((&a0)); params0 = HEX26_177447_2381377266(LOC10, ((NimStringDesc*) &T839829468_118)); { NI i_557964_839829468; NI HEX3Atmp_558025_839829468; NI LOC12; NI res_558028_839829468; i_557964_839829468 = (NI)0; HEX3Atmp_558025_839829468 = (NI)0; LOC12 = (NI)0; LOC12 = len_291081_850551059(n0); HEX3Atmp_558025_839829468 = (NI)(LOC12 - ((NI) 2)); res_558028_839829468 = ((NI) 1); { while (1) { Tnode290802* LOC15; Ropeobj177006* LOC16; if (!(res_558028_839829468 <= HEX3Atmp_558025_839829468)) goto LA14; i_557964_839829468 = res_558028_839829468; LOC15 = (Tnode290802*)0; LOC15 = HEX5BHEX5D_291238_850551059(n0, i_557964_839829468); initlocexpr_537283_839829468((*m0).initproc, LOC15, (&a0)); LOC16 = (Ropeobj177006*)0; LOC16 = rdloc_536188_839829468((&a0)); add_177482_2381377266(&params0, LOC16); add_177487_2381377266(&params0, ((NimStringDesc*) &T839829468_110)); res_558028_839829468 += ((NI) 1); } LA14: ; } } memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = tmp0; LOC17[1] = gettypedesc_533673_839829468(m0, (*sym0).typ); LOC17[2] = params0; LOC18 = (NimStringDesc*)0; LOC18 = HEX24_177856_2381377266(extname0); LOC17[3] = makecstring_189638_155036129(LOC18); load0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_235), LOC17, 4); last0 = lastson_293364_850551059(n0); { if (!((*last0).kind == ((Tnodekind290020) 58))) goto LA21; last0 = (*last0).kindU.S6.sons->data[((NI) 1)]; } LA21: ; { NimStringDesc* LOC27; if (!!(((*last0).kind == ((Tnodekind290020) 20)))) goto LA25; LOC27 = (NimStringDesc*)0; LOC27 = HEX24_194185_1689653243(T839829468_236); internalerror_194113_155036129(LOC27); } LA25: ; idx0 = (*last0).kindU.S3.strval; { Ropeobj177006** LOC32; if (!((idx0 ? idx0->Sup.len : 0) == ((NI) 0))) goto LA30; LOC32 = (Ropeobj177006**)0; LOC32 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 2)); add_177482_2381377266(LOC32, load0); } goto LA28; LA30: ; { NIM_BOOL LOC34; LOC34 = (NIM_BOOL)0; LOC34 = ((idx0 ? idx0->Sup.len : 0) == ((NI) 1)); if (!(LOC34)) goto LA35; LOC34 = (((NU8)(idx0->data[((NI) 0)])) >= ((NU8)(48)) && ((NU8)(idx0->data[((NI) 0)])) <= ((NU8)(57))); LA35: ; if (!LOC34) goto LA36; add_177482_2381377266(&(*m0).extensionloaders[(((NU8)(idx0->data[((NI) 0)])))- 48], load0); } goto LA28; LA36: ; { NimStringDesc* LOC39; LOC39 = (NimStringDesc*)0; LOC39 = rawNewString(idx0->Sup.len + 13); appendString(LOC39, ((NimStringDesc*) &T839829468_237)); appendString(LOC39, idx0); internalerror_194100_155036129((*sym0).info, LOC39); } LA28: ; } goto LA5; LA7: ; { TY533235 LOC41; NimStringDesc* LOC42; memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = tmp0; LOC41[1] = gettypedesc_533673_839829468(m0, (*sym0).typ); LOC41[2] = (*lib0).name; LOC42 = (NimStringDesc*)0; LOC42 = HEX24_177856_2381377266(extname0); LOC41[3] = makecstring_189638_155036129(LOC42); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_238), LOC41, 4); } LA5: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = (*sym0).loc.r; LOC43[1] = gettypedesc_533673_839829468(m0, (*sym0).loc.t); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_239), LOC43, 2); } N_NIMCALL(void, symindynamiclibpartial_558071_839829468)(Tcgen527027* m0, Tsym290834* sym0) { asgnRefNoCycle((void**) (&(*sym0).loc.r), mangledynlibproc_536816_839829468(sym0)); asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL); } N_NIMCALL(void, genprocnoforward_558906_839829468)(Tcgen527027* m0, Tsym290834* prc0) { { fillprocloc_537201_839829468(prc0); useheader_530369_839829468(m0, prc0); { Ropeobj177006* LOC5; if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 7))&15U)))!=0)) goto LA3; LOC5 = (Ropeobj177006*)0; LOC5 = cgsym_530403_839829468(m0, (*(*prc0).name).s); goto BeforeRet; } LA3: ; genprocprototype_537254_839829468(m0, prc0); { if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA8; } goto LA6; LA8: ; { if (!((*(*prc0).typ).callconv == ((Tcallingconvention290002) 5))) goto LA11; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*prc0).Sup.id); if (!!(LOC15)) goto LA16; genprocaux_558284_839829468(m0, prc0); } LA16: ; } goto LA6; LA11: ; { Tcgen527027* q0; if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA19; q0 = findpendingmodule_530241_839829468(m0, prc0); { NIM_BOOL LOC23; NIM_BOOL LOC25; LOC23 = (NIM_BOOL)0; LOC23 = !((q0 == NIM_NIL)); if (!(LOC23)) goto LA24; LOC25 = (NIM_BOOL)0; LOC25 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id); LOC23 = !(LOC25); LA24: ; if (!LOC23) goto LA26; symindynamiclib_557929_839829468(q0, prc0); } goto LA21; LA26: ; { symindynamiclibpartial_558071_839829468(m0, prc0); } LA21: ; } goto LA6; LA19: ; { Tcgen527027* q0; if (!!((((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0))) goto LA30; q0 = findpendingmodule_530241_839829468(m0, prc0); { NIM_BOOL LOC34; NIM_BOOL LOC36; LOC34 = (NIM_BOOL)0; LOC34 = !((q0 == NIM_NIL)); if (!(LOC34)) goto LA35; LOC36 = (NIM_BOOL)0; LOC36 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id); LOC34 = !(LOC36); LA35: ; if (!LOC34) goto LA37; genprocaux_558284_839829468(q0, prc0); } LA37: ; } goto LA6; LA30: ; LA6: ; }BeforeRet: ; } N_NIMCALL(void, genproc_530951_839829468)(Tcgen527027* m0, Tsym290834* prc0) { { { NIM_BOOL LOC3; NIM_BOOL LOC5; LOC3 = (NIM_BOOL)0; LOC3 = (((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 26))&31U)))!=0); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = isactivated_559431_839829468(prc0); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; goto BeforeRet; } LA6: ; fillprocloc_537201_839829468(prc0); { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 4))&31U)))!=0)) goto LA10; addforwardedproc_530203_839829468(m0, prc0); } goto LA8; LA10: ; { genprocnoforward_558906_839829468(m0, prc0); { NIM_BOOL LOC15; NIM_BOOL LOC16; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC16 = ((65600 & (*prc0).flags) == 64); if (!(LOC16)) goto LA17; LOC16 = !((generatedheader_530201_839829468 == NIM_NIL)); LA17: ; LOC15 = LOC16; if (!(LOC15)) goto LA18; LOC15 = !((((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)); LA18: ; if (!LOC15) goto LA19; genprocprototype_537254_839829468(generatedheader_530201_839829468, prc0); { if (!((*(*prc0).typ).callconv == ((Tcallingconvention290002) 5))) goto LA23; { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = containsorincl_266862_2627731572((&(*generatedheader_530201_839829468).declaredthings), (*prc0).Sup.id); if (!!(LOC27)) goto LA28; genprocaux_558284_839829468(generatedheader_530201_839829468, prc0); } LA28: ; } LA23: ; } LA19: ; } LA8: ; }BeforeRet: ; } static N_INLINE(NIM_BOOL, emulatedthreadvars_530949_839829468)(void) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((71303168 & ~ gglobaloptions_168130_2607990831)==0); return result0; } N_NIMCALL(void, declarethreadvar_536676_839829468)(Tcgen527027* m0, Tsym290834* s0, NIM_BOOL isextern0) { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = emulatedthreadvars_530949_839829468(); if (!LOC3) goto LA4; { NIM_BOOL LOC8; TY530811 LOC11; LOC8 = (NIM_BOOL)0; LOC8 = containsorincl_266862_2627731572((&nimtvdeclared_536675_839829468), (*s0).Sup.id); if (!!(LOC8)) goto LA9; nimtvdeps_536674_839829468 = (Ttypeseq290836*) incrSeqV2(&(nimtvdeps_536674_839829468)->Sup, sizeof(Ttype290840*)); asgnRefNoCycle((void**) (&nimtvdeps_536674_839829468->data[nimtvdeps_536674_839829468->Sup.len]), (*s0).loc.t); ++nimtvdeps_536674_839829468->Sup.len; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_533673_839829468(m0, (*s0).loc.t); LOC11[1] = (*s0).loc.r; addf_178205_2381377266(&nimtv_536656_839829468, ((NimStringDesc*) &T839829468_54), LOC11, 2); } LA9: ; } goto LA1; LA4: ; { Ropeobj177006* LOC21; TY177507 LOC22; { if (!isextern0) goto LA15; add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_240)); } LA15: ; { if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 22))&63U)))!=0)) goto LA19; add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_241)); } LA19: ; LOC21 = (Ropeobj177006*)0; LOC21 = gettypedesc_533673_839829468(m0, (*s0).loc.t); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], LOC21); memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = (*s0).loc.r; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC22, 1); } LA1: ; } N_NIMCALL(void, genvarprototypeaux_542254_839829468)(Tcgen527027* m0, Tsym290834* sym0) { Ropeobj177006* LOC1; { useheader_530369_839829468(m0, sym0); LOC1 = (Ropeobj177006*)0; LOC1 = manglename_531205_839829468(sym0); fillloc_530282_839829468((&(*sym0).loc), ((Tlockind290808) 3), (*sym0).typ, LOC1, ((Tstorageloc290812) 3)); { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0); if (LOC4) goto LA5; LOC4 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LA5: ; if (!LOC4) goto LA6; goto BeforeRet; } LA6: ; { if (!!(((*(*sym0).owner).Sup.id == (*(*m0).module).Sup.id))) goto LA10; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0)) goto LA14; declarethreadvar_536676_839829468(m0, sym0, NIM_TRUE); } goto LA12; LA14: ; { Ropeobj177006* LOC17; TY177507 LOC30; add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_240)); LOC17 = (Ropeobj177006*)0; LOC17 = gettypedesc_533673_839829468(m0, (*sym0).loc.t); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], LOC17); { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA20; add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_53)); } LA20: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 8))&31U)))!=0)) goto LA24; add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_121)); } LA24: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 7))&31U)))!=0)) goto LA28; add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_122)); } LA28: ; memset((void*)LOC30, 0, sizeof(LOC30)); LOC30[0] = (*sym0).loc.r; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC30, 1); } LA12: ; } LA10: ; }BeforeRet: ; } N_NIMCALL(void, genvarprototype_537236_839829468)(Tcgen527027* m0, Tsym290834* sym0) { genvarprototypeaux_542254_839829468(m0, sym0); } N_NIMCALL(Ropeobj177006*, cgsym_530403_839829468)(Tcgen527027* m0, NimStringDesc* name0) { Ropeobj177006* result0; Tsym290834* sym0; result0 = (Ropeobj177006*)0; sym0 = getcompilerproc_336748_3937434831(name0); { if (!!((sym0 == NIM_NIL))) goto LA3; switch ((*sym0).kind) { case ((Tsymkind290435) 12): case ((Tsymkind290435) 13): case ((Tsymkind290435) 15): case ((Tsymkind290435) 14): { genproc_530951_839829468(m0, sym0); } break; case ((Tsymkind290435) 8): case ((Tsymkind290435) 11): case ((Tsymkind290435) 9): { genvarprototype_537236_839829468(m0, sym0); } break; case ((Tsymkind290435) 7): { Ropeobj177006* LOC8; LOC8 = (Ropeobj177006*)0; LOC8 = gettypedesc_533673_839829468(m0, (*sym0).typ); } break; default: { NimStringDesc* LOC10; LOC10 = (NimStringDesc*)0; LOC10 = rawNewString(name0->Sup.len + reprEnum((NI)(*sym0).kind, (&NTI290435))->Sup.len + 9); appendString(LOC10, ((NimStringDesc*) &T839829468_243)); appendString(LOC10, name0); appendString(LOC10, ((NimStringDesc*) &T839829468_244)); appendString(LOC10, reprEnum((NI)(*sym0).kind, (&NTI290435))); internalerror_194113_155036129(LOC10); } break; } } goto LA1; LA3: ; { rawmessage_192612_155036129(((Tmsgkind189002) 68), name0); } LA1: ; result0 = (*sym0).loc.r; return result0; } N_NIMCALL(Ropeobj177006*, ropecg_530407_839829468)(Tcgen527027* m0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006* result0; NI i0; NI length0; NI num0; result0 = (Ropeobj177006*)0; i0 = ((NI) 0); length0 = (frmt0 ? frmt0->Sup.len : 0); result0 = NIM_NIL; num0 = ((NI) 0); { while (1) { NI start0; if (!(i0 < length0)) goto LA2; { if (!((NU8)(frmt0->data[i0]) == (NU8)(36))) goto LA5; i0 += ((NI) 1); switch (((NU8)(frmt0->data[i0]))) { case 36: { add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_19)); i0 += ((NI) 1); } break; case 35: { i0 += ((NI) 1); add_177482_2381377266(&result0, args0[num0]); num0 += ((NI) 1); } break; case 48 ... 57: { NI j0; j0 = ((NI) 0); { while (1) { j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48)); i0 += ((NI) 1); { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = (length0 <= i0); if (LOC14) goto LA15; LOC14 = !((((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))); LA15: ; if (!LOC14) goto LA16; goto LA10; } LA16: ; } } LA10: ; num0 = j0; { NimStringDesc* LOC22; NimStringDesc* LOC23; if (!((NI)((args0Len0-1) + ((NI) 1)) < j0)) goto LA20; LOC22 = (NimStringDesc*)0; LOC23 = (NimStringDesc*)0; LOC23 = nimIntToStr(j0); LOC22 = rawNewString(LOC23->Sup.len + 30); appendString(LOC22, ((NimStringDesc*) &T839829468_20)); appendString(LOC22, LOC23); internalerror_194113_155036129(LOC22); } LA20: ; add_177482_2381377266(&result0, args0[(NI)(j0 - ((NI) 1))]); } break; case 110: { { if (!!(((goptions_168128_2607990831 &(1U<<((NU)(((Toption168009) 10))&31U)))!=0))) goto LA27; add_177482_2381377266(&result0, rnl_177903_2381377266); } LA27: ; i0 += ((NI) 1); } break; case 78: { add_177482_2381377266(&result0, rnl_177903_2381377266); i0 += ((NI) 1); } break; default: { NimStringDesc* LOC31; LOC31 = (NimStringDesc*)0; LOC31 = rawNewString(31); appendString(LOC31, ((NimStringDesc*) &T839829468_20)); appendChar(LOC31, frmt0->data[i0]); internalerror_194113_155036129(LOC31); } break; } } goto LA3; LA5: ; { NIM_BOOL LOC33; NI j0; NimStringDesc* ident0; Ropeobj177006* LOC39; LOC33 = (NIM_BOOL)0; LOC33 = ((NU8)(frmt0->data[i0]) == (NU8)(35)); if (!(LOC33)) goto LA34; LOC33 = (((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(97)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(122)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(65)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(90)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(95))); LA34: ; if (!LOC33) goto LA35; i0 += ((NI) 1); j0 = i0; { while (1) { if (!(((NU8)(frmt0->data[j0])) >= ((NU8)(97)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(122)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(65)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(90)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(57)) || ((NU8)(frmt0->data[j0])) == ((NU8)(95)))) goto LA38; j0 += ((NI) 1); } LA38: ; } ident0 = copyStrLast(frmt0, i0, (NI)(j0 - ((NI) 1))); i0 = j0; LOC39 = (Ropeobj177006*)0; LOC39 = cgsym_530403_839829468(m0, ident0); add_177482_2381377266(&result0, LOC39); } goto LA3; LA35: ; { NIM_BOOL LOC41; NI j0; NimStringDesc* LOC47; Ropeobj177006* LOC48; LOC41 = (NIM_BOOL)0; LOC41 = ((NU8)(frmt0->data[i0]) == (NU8)(35)); if (!(LOC41)) goto LA42; LOC41 = ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(36)); LA42: ; if (!LOC41) goto LA43; i0 += ((NI) 2); j0 = ((NI) 0); { while (1) { if (!(((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))) goto LA46; j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48)); i0 += ((NI) 1); } LA46: ; } LOC47 = (NimStringDesc*)0; LOC47 = HEX24_177856_2381377266(args0[(NI)(j0 - ((NI) 1))]); LOC48 = (Ropeobj177006*)0; LOC48 = cgsym_530403_839829468(m0, LOC47); add_177482_2381377266(&result0, LOC48); } goto LA3; LA43: ; LA3: ; start0 = i0; { while (1) { if (!(i0 < length0)) goto LA50; { NIM_BOOL LOC53; LOC53 = (NIM_BOOL)0; LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(36))); if (!(LOC53)) goto LA54; LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(35))); LA54: ; if (!LOC53) goto LA55; i0 += ((NI) 1); } goto LA51; LA55: ; { goto LA49; } LA51: ; } LA50: ; } LA49: ; { NimStringDesc* LOC62; if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA60; LOC62 = (NimStringDesc*)0; LOC62 = copyStrLast(frmt0, start0, (NI)(i0 - ((NI) 1))); add_177487_2381377266(&result0, LOC62); } LA60: ; } LA2: ; } return result0; } static N_INLINE(NIM_BOOL, crossescppboundary_558754_839829468)(Tcgen527027* m0, Tsym290834* sym0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; Tsym290834* LOC4; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); if (!(LOC2)) goto LA3; LOC4 = (Tsym290834*)0; LOC4 = getmodule_297123_2984716966(sym0); LOC2 = !((((*LOC4).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0)); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA5; LOC1 = !((gcmd_168132_2607990831 == ((Tcommands168076) 2))); LA5: ; result0 = LOC1; return result0; } N_NIMCALL(void, genprocprototype_537254_839829468)(Tcgen527027* m0, Tsym290834* sym0) { { useheader_530369_839829468(m0, sym0); { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA3; goto BeforeRet; } LA3: ; { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA7; { NIM_BOOL LOC11; Tsym290834* LOC12; NIM_BOOL LOC14; TY530811 LOC17; Ropeobj177006* LOC18; LOC11 = (NIM_BOOL)0; LOC12 = (Tsym290834*)0; LOC12 = getmodule_297123_2984716966(sym0); LOC11 = !(((*LOC12).Sup.id == (*(*m0).module).Sup.id)); if (!(LOC11)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LOC11 = !(LOC14); LA13: ; if (!LOC11) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_533673_839829468(m0, (*sym0).loc.t); LOC17[1] = mangledynlibproc_536816_839829468(sym0); LOC18 = (Ropeobj177006*)0; LOC18 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_245), LOC17, 2); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], LOC18); } LA15: ; } goto LA5; LA7: ; { NIM_BOOL LOC20; Ropeobj177006* header0; TY177507 LOC47; Ropeobj177006* LOC48; LOC20 = (NIM_BOOL)0; LOC20 = containsorincl_266862_2627731572((&(*m0).declaredprotos), (*sym0).Sup.id); if (!!(LOC20)) goto LA21; header0 = genprocheader_533867_839829468(m0, sym0); { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 14))&31U)))!=0); if (!(LOC25)) goto LA26; LOC25 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 6))&7U)))!=0); LA26: ; if (!LOC25) goto LA27; header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_213), header0); } LA27: ; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = !(((*(*sym0).typ).callconv == ((Tcallingconvention290002) 5))); if (!(LOC31)) goto LA32; LOC31 = crossescppboundary_558754_839829468(m0, sym0); LA32: ; if (!LOC31) goto LA33; header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_246), header0); } LA33: ; { NIM_BOOL LOC37; LOC37 = (NIM_BOOL)0; LOC37 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0); if (!(LOC37)) goto LA38; LOC37 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 7))&7U)))!=0); LA38: ; if (!LOC37) goto LA39; add_177487_2381377266(&header0, ((NimStringDesc*) &T839829468_247)); } LA39: ; { NIM_BOOL LOC43; LOC43 = (NIM_BOOL)0; LOC43 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 14))&31U)))!=0); if (!(LOC43)) goto LA44; LOC43 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 7))&7U)))!=0); LA44: ; if (!LOC43) goto LA45; add_177487_2381377266(&header0, ((NimStringDesc*) &T839829468_248)); } LA45: ; memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = header0; LOC48 = (Ropeobj177006*)0; LOC48 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_191), LOC47, 1); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], LOC48); } goto LA5; LA21: ; LA5: ; }BeforeRet: ; } static N_INLINE(NIM_BOOL, usesnativegc_168177_2607990831)(void) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = (((Tgcmode168080) 5) <= gselectedgc_168133_2607990831); return result0; } N_NIMCALL(void, genrefassign_536311_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; TY530811 LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((*dest0).s == ((Tstorageloc290812) 2)); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = usesnativegc_168177_2607990831(); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_536188_839829468(dest0); LOC8[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC8, 2); } goto LA1; LA6: ; { if (!((*dest0).s == ((Tstorageloc290812) 3))) goto LA10; { NIM_BOOL LOC14; TY530811 LOC17; LOC14 = (NIM_BOOL)0; LOC14 = canformacycle_318123_3876443242((*dest0).t); if (!LOC14) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_536204_839829468(dest0); LOC17[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_249), LOC17, 2); } goto LA12; LA15: ; { TY530811 LOC19; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_536204_839829468(dest0); LOC19[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_250), LOC19, 2); } LA12: ; } goto LA1; LA10: ; { TY530811 LOC21; memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = addrloc_536204_839829468(dest0); LOC21[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_251), LOC21, 2); } LA1: ; } N_NIMCALL(void, optasgnloc_547789_839829468)(Tloc290816* a0, Ttype290840* t0, Ropeobj177006* field0, Tloc290816* Result) { Ropeobj177006* LOC1; Ropeobj177006* LOC2; (*Result).k = ((Tlockind290808) 5); (*Result).s = (*a0).s; unsureAsgnRef((void**) (&(*Result).t), t0); LOC1 = (Ropeobj177006*)0; LOC1 = rdloc_536188_839829468(a0); LOC2 = (Ropeobj177006*)0; LOC2 = HEX26_177447_2381377266(LOC1, ((NimStringDesc*) &T839829468_257)); unsureAsgnRef((void**) (&(*Result).r), HEX26_177418_2381377266(LOC2, field0)); } N_NIMCALL(void, genoptasgntuple_548001_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0) { Tassignmentflag536302Set newflags0; Ttype290840* t_548053_839829468; Ttype290840* LOC9; { if (!((*src0).s == ((Tstorageloc290812) 1))) goto LA3; newflags0 = (flags0 | 1); } goto LA1; LA3: ; { if (!(((*(*dest0).t).flags &(1U<<((NU)(((Ttypeflag290431) 6))&31U)))!=0)) goto LA6; newflags0 = (flags0 & ~ 1); } goto LA1; LA6: ; { newflags0 = flags0; } LA1: ; LOC9 = (Ttype290840*)0; LOC9 = skiptypes_294099_850551059((*dest0).t, IL64(211106232576256)); t_548053_839829468 = getuniquetype_526640_2036603609(LOC9); { NI i_548071_839829468; NI HEX3Atmp_548077_839829468; NI LOC11; NI res_548080_839829468; i_548071_839829468 = (NI)0; HEX3Atmp_548077_839829468 = (NI)0; LOC11 = (NI)0; LOC11 = len_293339_850551059(t_548053_839829468); HEX3Atmp_548077_839829468 = (LOC11 - 1); res_548080_839829468 = ((NI) 0); { while (1) { Ttype290840* t0; Ropeobj177006* field0; TY177507 LOC14; Tloc290816 LOC15; Tloc290816 LOC16; if (!(res_548080_839829468 <= HEX3Atmp_548077_839829468)) goto LA13; i_548071_839829468 = res_548080_839829468; t0 = (*t_548053_839829468).sons->data[i_548071_839829468]; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_177401_2381377266(((NI64) (i_548071_839829468))); field0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_260), LOC14, 1); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_547789_839829468(dest0, t0, field0, (&LOC15)); memset((void*)(&LOC16), 0, sizeof(LOC16)); optasgnloc_547789_839829468(src0, t0, field0, (&LOC16)); genassignment_537264_839829468(p0, (&LOC15), (&LOC16), newflags0); res_548080_839829468 += ((NI) 1); } LA13: ; } } } N_NIMCALL(void, gengenericasgn_548167_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0) { { NIM_BOOL LOC3; Ttype290840* LOC5; LOC3 = (NIM_BOOL)0; LOC3 = !(((flags0 &(1U<<((NU)(((Tassignmentflag536302) 0))&7U)))!=0)); if (LOC3) goto LA4; LOC5 = (Ttype290840*)0; LOC5 = skiptypes_294099_850551059((*dest0).t, IL64(211106242013440)); LOC3 = (((*LOC5).flags &(1U<<((NU)(((Ttypeflag290431) 6))&31U)))!=0); LA4: ; if (!LOC3) goto LA6; { NIM_BOOL LOC10; NIM_BOOL LOC12; TY533238 LOC15; LOC10 = (NIM_BOOL)0; LOC10 = ((*dest0).s == ((Tstorageloc290812) 2)); if (LOC10) goto LA11; LOC12 = (NIM_BOOL)0; LOC12 = usesnativegc_168177_2607990831(); LOC10 = !(LOC12); LA11: ; if (!LOC10) goto LA13; usestringh_530345_839829468((*p0).module); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = addrloc_536204_839829468(dest0); LOC15[1] = addrloc_536204_839829468(src0); LOC15[2] = rdloc_536188_839829468(dest0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_261), LOC15, 3); } goto LA8; LA13: ; { TY533238 LOC17; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_536204_839829468(dest0); LOC17[1] = addrloc_536204_839829468(src0); LOC17[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_262), LOC17, 3); } LA8: ; } goto LA1; LA6: ; { TY533238 LOC19; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_536204_839829468(dest0); LOC19[1] = addrloc_536204_839829468(src0); LOC19[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_263), LOC19, 3); } LA1: ; } N_NIMCALL(NI, asgncomplexity_547751_839829468)(Tnode290802* n0) { NI result0; result0 = (NI)0; { if (!!((n0 == NIM_NIL))) goto LA3; switch ((*n0).kind) { case ((Tnodekind290020) 3): { result0 = ((NI) 1); } break; case ((Tnodekind290020) 139): { result0 = ((NI) 100); } break; case ((Tnodekind290020) 138): { { Tnode290802* t_547768_839829468; t_547768_839829468 = (Tnode290802*)0; { NI i_547782_839829468; NI HEX3Atmp_547784_839829468; NI LOC10; NI res_547786_839829468; i_547782_839829468 = (NI)0; HEX3Atmp_547784_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = len_291081_850551059(n0); HEX3Atmp_547784_839829468 = (LOC10 - 1); res_547786_839829468 = ((NI) 0); { while (1) { NI LOC13; if (!(res_547786_839829468 <= HEX3Atmp_547784_839829468)) goto LA12; i_547782_839829468 = res_547786_839829468; t_547768_839829468 = (*n0).kindU.S6.sons->data[i_547782_839829468]; LOC13 = (NI)0; LOC13 = asgncomplexity_547751_839829468(t_547768_839829468); result0 += LOC13; res_547786_839829468 += ((NI) 1); } LA12: ; } } } } break; default: { } break; } } LA3: ; return result0; } N_NIMCALL(void, genoptasgnobject_548084_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0, Tnode290802* t0) { Tassignmentflag536302Set newflags0; { { if (!(t0 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; { if (!((*src0).s == ((Tstorageloc290812) 1))) goto LA7; newflags0 = (flags0 | 1); } goto LA5; LA7: ; { if (!(((*(*dest0).t).flags &(1U<<((NU)(((Ttypeflag290431) 6))&31U)))!=0)) goto LA10; newflags0 = (flags0 & ~ 1); } goto LA5; LA10: ; { newflags0 = flags0; } LA5: ; switch ((*t0).kind) { case ((Tnodekind290020) 3): { Tsym290834* field0; Tloc290816 LOC14; Tloc290816 LOC15; field0 = (*t0).kindU.S4.sym; memset((void*)(&LOC14), 0, sizeof(LOC14)); optasgnloc_547789_839829468(dest0, (*field0).typ, (*field0).loc.r, (&LOC14)); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_547789_839829468(src0, (*field0).typ, (*field0).loc.r, (&LOC15)); genassignment_537264_839829468(p0, (&LOC14), (&LOC15), newflags0); } break; case ((Tnodekind290020) 138): { { Tnode290802* child_548155_839829468; child_548155_839829468 = (Tnode290802*)0; { NI i_548160_839829468; NI HEX3Atmp_548162_839829468; NI LOC19; NI res_548164_839829468; i_548160_839829468 = (NI)0; HEX3Atmp_548162_839829468 = (NI)0; LOC19 = (NI)0; LOC19 = len_291081_850551059(t0); HEX3Atmp_548162_839829468 = (LOC19 - 1); res_548164_839829468 = ((NI) 0); { while (1) { if (!(res_548164_839829468 <= HEX3Atmp_548162_839829468)) goto LA21; i_548160_839829468 = res_548164_839829468; child_548155_839829468 = (*t0).kindU.S6.sons->data[i_548160_839829468]; genoptasgnobject_548084_839829468(p0, dest0, src0, newflags0, child_548155_839829468); res_548164_839829468 += ((NI) 1); } LA21: ; } } } } break; default: { } break; } }BeforeRet: ; } N_NIMCALL(void, genassignment_537264_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0, Tassignmentflag536302Set flags0) { Ttype290840* ty0; { { NIM_BOOL LOC3; TY530811 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = !(((*src0).t == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = ((*(*src0).t).kind == ((Ttypekind290244) 21)); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_536188_839829468(dest0); LOC7[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC7, 2); goto BeforeRet; } LA5: ; ty0 = skiptypes_294099_850551059((*dest0).t, IL64(211106233624832)); switch ((*ty0).kind) { case ((Ttypekind290244) 22): { genrefassign_536311_839829468(p0, dest0, src0, flags0); } break; case ((Ttypekind290244) 24): { { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = !(((flags0 &(1U<<((NU)(((Tassignmentflag536302) 0))&7U)))!=0)); if (!(LOC12)) goto LA13; LOC12 = !(((*src0).s == ((Tstorageloc290812) 1))); LA13: ; if (!LOC12) goto LA14; genrefassign_536311_839829468(p0, dest0, src0, flags0); } goto LA10; LA14: ; { TY533238 LOC17; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_536204_839829468(dest0); LOC17[1] = rdloc_536188_839829468(src0); LOC17[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_252), LOC17, 3); } LA10: ; } break; case ((Ttypekind290244) 28): { { NIM_BOOL LOC21; LOC21 = (NIM_BOOL)0; LOC21 = !(((flags0 &(1U<<((NU)(((Tassignmentflag536302) 0))&7U)))!=0)); if (!(LOC21)) goto LA22; LOC21 = !(((*src0).s == ((Tstorageloc290812) 1))); LA22: ; if (!LOC21) goto LA23; genrefassign_536311_839829468(p0, dest0, src0, flags0); } goto LA19; LA23: ; { { NIM_BOOL LOC28; NIM_BOOL LOC30; TY530811 LOC33; LOC28 = (NIM_BOOL)0; LOC28 = ((*dest0).s == ((Tstorageloc290812) 2)); if (LOC28) goto LA29; LOC30 = (NIM_BOOL)0; LOC30 = usesnativegc_168177_2607990831(); LOC28 = !(LOC30); LA29: ; if (!LOC28) goto LA31; memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rdloc_536188_839829468(dest0); LOC33[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_253), LOC33, 2); } goto LA26; LA31: ; { Tloc290816 tmp0; TY533238 LOC37; TY177507 LOC38; if (!((*dest0).s == ((Tstorageloc290812) 3))) goto LA35; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_535032_839829468(p0, ty0, (&tmp0), NIM_FALSE); memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = rdloc_536188_839829468(dest0); LOC37[1] = rdloc_536188_839829468(src0); LOC37[2] = rdloc_536188_839829468((&tmp0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_254), LOC37, 3); memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = rdloc_536188_839829468((&tmp0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_255), LOC38, 1); } goto LA26; LA35: ; { TY530811 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = addrloc_536204_839829468(dest0); LOC40[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_256), LOC40, 2); } LA26: ; } LA19: ; } break; case ((Ttypekind290244) 25): { { NIM_BOOL LOC44; Tloc290816 a0; Ropeobj177006* LOC47; Tloc290816 LOC48; Tloc290816 b0; Ropeobj177006* LOC49; Tloc290816 LOC50; TY530811 LOC51; LOC44 = (NIM_BOOL)0; LOC44 = needscomplexassignment_531511_839829468((*dest0).t); if (!LOC44) goto LA45; memset((void*)(&a0), 0, sizeof(a0)); LOC47 = (Ropeobj177006*)0; LOC47 = rope_177277_2381377266(((NimStringDesc*) &T839829468_258)); memset((void*)(&LOC48), 0, sizeof(LOC48)); optasgnloc_547789_839829468(dest0, (*dest0).t, LOC47, (&LOC48)); memcpy((void*)(&a0), (NIM_CONST void*)(&LOC48), sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); LOC49 = (Ropeobj177006*)0; LOC49 = rope_177277_2381377266(((NimStringDesc*) &T839829468_258)); memset((void*)(&LOC50), 0, sizeof(LOC50)); optasgnloc_547789_839829468(src0, (*dest0).t, LOC49, (&LOC50)); memcpy((void*)(&b0), (NIM_CONST void*)(&LOC50), sizeof(b0)); genrefassign_536311_839829468(p0, (&a0), (&b0), flags0); memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = rdloc_536188_839829468(dest0); LOC51[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_259), LOC51, 2); } goto LA42; LA45: ; { TY530811 LOC53; memset((void*)LOC53, 0, sizeof(LOC53)); LOC53[0] = rdloc_536188_839829468(dest0); LOC53[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC53, 2); } LA42: ; } break; case ((Ttypekind290244) 18): { { NIM_BOOL LOC57; LOC57 = (NIM_BOOL)0; LOC57 = needscomplexassignment_531511_839829468((*dest0).t); if (!LOC57) goto LA58; { NI LOC62; LOC62 = (NI)0; LOC62 = len_293339_850551059((*dest0).t); if (!(LOC62 <= ((NI) 4))) goto LA63; genoptasgntuple_548001_839829468(p0, dest0, src0, flags0); } goto LA60; LA63: ; { gengenericasgn_548167_839829468(p0, dest0, src0, flags0); } LA60: ; } goto LA55; LA58: ; { TY530811 LOC67; memset((void*)LOC67, 0, sizeof(LOC67)); LOC67[0] = rdloc_536188_839829468(dest0); LOC67[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC67, 2); } LA55: ; } break; case ((Ttypekind290244) 17): { { NIM_BOOL LOC71; TY530811 LOC74; LOC71 = (NIM_BOOL)0; LOC71 = isimportedcpptype_531478_839829468(ty0); if (!LOC71) goto LA72; memset((void*)LOC74, 0, sizeof(LOC74)); LOC74[0] = rdloc_536188_839829468(dest0); LOC74[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC74, 2); } goto LA69; LA72: ; { NIM_BOOL LOC76; LOC76 = (NIM_BOOL)0; LOC76 = isobjlackingtypefield_531515_839829468(ty0); if (!!(LOC76)) goto LA77; gengenericasgn_548167_839829468(p0, dest0, src0, flags0); } goto LA69; LA77: ; { NIM_BOOL LOC80; LOC80 = (NIM_BOOL)0; LOC80 = needscomplexassignment_531511_839829468(ty0); if (!LOC80) goto LA81; { NIM_BOOL LOC85; NI LOC87; Ropeobj177006* LOC90; LOC85 = (NIM_BOOL)0; LOC85 = (*ty0).sons->data[((NI) 0)] == 0; if (!(LOC85)) goto LA86; LOC87 = (NI)0; LOC87 = asgncomplexity_547751_839829468((*ty0).n); LOC85 = (LOC87 <= ((NI) 4)); LA86: ; if (!LOC85) goto LA88; LOC90 = (Ropeobj177006*)0; LOC90 = gettypedesc_533673_839829468((*p0).module, ty0); ty0 = getuniquetype_526640_2036603609(ty0); { NimStringDesc* LOC95; if (!!(!(((*ty0).n == NIM_NIL)))) goto LA93; LOC95 = (NimStringDesc*)0; LOC95 = HEX24_194185_1689653243(T839829468_264); internalerror_194113_155036129(LOC95); } LA93: ; genoptasgnobject_548084_839829468(p0, dest0, src0, flags0, (*ty0).n); } goto LA83; LA88: ; { gengenericasgn_548167_839829468(p0, dest0, src0, flags0); } LA83: ; } goto LA69; LA81: ; { TY530811 LOC98; memset((void*)LOC98, 0, sizeof(LOC98)); LOC98[0] = rdloc_536188_839829468(dest0); LOC98[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC98, 2); } LA69: ; } break; case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { { NIM_BOOL LOC102; LOC102 = (NIM_BOOL)0; LOC102 = needscomplexassignment_531511_839829468((*dest0).t); if (!LOC102) goto LA103; gengenericasgn_548167_839829468(p0, dest0, src0, flags0); } goto LA100; LA103: ; { TY533238 LOC106; usestringh_530345_839829468((*p0).module); memset((void*)LOC106, 0, sizeof(LOC106)); LOC106[0] = rdloc_536188_839829468(dest0); LOC106[1] = rdloc_536188_839829468(src0); LOC106[2] = gettypedesc_533673_839829468((*p0).module, ty0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_261), LOC106, 3); } LA100: ; } break; case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { { NIM_BOOL LOC110; TY533238 LOC113; LOC110 = (NIM_BOOL)0; LOC110 = needscomplexassignment_531511_839829468((*dest0).t); if (!LOC110) goto LA111; memset((void*)LOC113, 0, sizeof(LOC113)); LOC113[0] = addrloc_536204_839829468(dest0); LOC113[1] = addrloc_536204_839829468(src0); LOC113[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_266), LOC113, 3); } goto LA108; LA111: ; { TY530811 LOC115; usestringh_530345_839829468((*p0).module); memset((void*)LOC115, 0, sizeof(LOC115)); LOC115[0] = rdloc_536188_839829468(dest0); LOC115[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_267), LOC115, 2); } LA108: ; } break; case ((Ttypekind290244) 19): { { Tctypekind527007 LOC119; TY533238 LOC122; NI64 LOC123; LOC119 = (Tctypekind527007)0; LOC119 = maptype_531394_839829468(ty0); if (!(LOC119 == ((Tctypekind527007) 17))) goto LA120; usestringh_530345_839829468((*p0).module); memset((void*)LOC122, 0, sizeof(LOC122)); LOC122[0] = rdloc_536188_839829468(dest0); LOC122[1] = rdloc_536188_839829468(src0); LOC123 = (NI64)0; LOC123 = getsize_318135_3876443242((*dest0).t); LOC122[2] = rope_177401_2381377266(LOC123); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_268), LOC122, 3); } goto LA117; LA120: ; { TY530811 LOC125; memset((void*)LOC125, 0, sizeof(LOC125)); LOC125[0] = rdloc_536188_839829468(dest0); LOC125[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC125, 2); } LA117: ; } break; case ((Ttypekind290244) 21): case ((Ttypekind290244) 26): case ((Ttypekind290244) 2): case ((Ttypekind290244) 1): case ((Ttypekind290244) 14): case ((Ttypekind290244) 29): case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44): case ((Ttypekind290244) 20): case ((Ttypekind290244) 23): { TY530811 LOC127; memset((void*)LOC127, 0, sizeof(LOC127)); LOC127[0] = rdloc_536188_839829468(dest0); LOC127[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC127, 2); } break; default: { NimStringDesc* LOC129; LOC129 = (NimStringDesc*)0; LOC129 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI290244))->Sup.len + 15); appendString(LOC129, ((NimStringDesc*) &T839829468_269)); appendString(LOC129, reprEnum((NI)(*ty0).kind, (&NTI290244))); internalerror_194113_155036129(LOC129); } break; } }BeforeRet: ; } N_NIMCALL(void, putlocintodest_537258_839829468)(Tcproc527021* p0, Tloc290816* d0, Tloc290816* s0) { { if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag290810) 2))&15U)))!=0)) goto LA7; genassignment_537264_839829468(p0, (&(*d0)), s0, 0); } goto LA5; LA7: ; { genassignment_537264_839829468(p0, (&(*d0)), s0, 1); } LA5: ; } goto LA1; LA3: ; { genericAssign((void*)(&(*d0)), (void*)s0, (&NTI290816)); } LA1: ; } N_NIMCALL(NIM_BOOL, issimpleconst_530311_839829468)(Ttype290840* typ0) { NIM_BOOL result0; Ttype290840* t0; NIM_BOOL LOC1; NIM_BOOL LOC3; result0 = (NIM_BOOL)0; t0 = skiptypes_294099_850551059(typ0, IL64(211106240964864)); LOC1 = (NIM_BOOL)0; LOC1 = !(((17760272 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)); if (!(LOC1)) goto LA2; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind290244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention290002) 8)); LA4: ; LOC1 = !(LOC3); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, putintodest_548468_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0, Tstorageloc290812 s0) { Tloc290816 a0; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3; initloc_530273_839829468((&a0), ((Tlockind290808) 6), t0, s0); a0.r = r0; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag290810) 2))&15U)))!=0)) goto LA7; genassignment_537264_839829468(p0, (&(*d0)), (&a0), 0); } goto LA5; LA7: ; { genassignment_537264_839829468(p0, (&(*d0)), (&a0), 1); } LA5: ; } goto LA1; LA3: ; { (*d0).k = ((Tlockind290808) 6); unsureAsgnRef((void**) (&(*d0).t), t0); unsureAsgnRef((void**) (&(*d0).r), r0); } LA1: ; } N_NIMCALL(NI64, bitsettoword_547578_839829468)(Tbitset337004* s0, NI size0) { NI64 result0; result0 = (NI64)0; result0 = IL64(0); { NI j_547612_839829468; NI HEX3Atmp_547622_839829468; NI res_547625_839829468; j_547612_839829468 = (NI)0; HEX3Atmp_547622_839829468 = (NI)0; HEX3Atmp_547622_839829468 = (NI)(size0 - ((NI) 1)); res_547625_839829468 = ((NI) 0); { while (1) { if (!(res_547625_839829468 <= HEX3Atmp_547622_839829468)) goto LA3; j_547612_839829468 = res_547625_839829468; { if (!(j_547612_839829468 < (s0 ? s0->Sup.len : 0))) goto LA6; result0 = (NI64)(result0 | (NI64)((NU64)(((NI64)(NU64)(NU8)(s0->data[j_547612_839829468]))) << (NU64)(((NI64) ((NI)(j_547612_839829468 * ((NI) 8))))))); } LA6: ; res_547625_839829468 += ((NI) 1); } LA3: ; } } return result0; } N_NIMCALL(Ropeobj177006*, genrawsetdata_547629_839829468)(Tbitset337004* cs0, NI size0) { Ropeobj177006* result0; NimStringDesc* frmt0; result0 = (Ropeobj177006*)0; frmt0 = (NimStringDesc*)0; { TY531289 LOC5; if (!(((NI) 8) < size0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_273), LOC5, 0); { NI i_547649_839829468; NI HEX3Atmp_547657_839829468; NI res_547660_839829468; i_547649_839829468 = (NI)0; HEX3Atmp_547657_839829468 = (NI)0; HEX3Atmp_547657_839829468 = (NI)(size0 - ((NI) 1)); res_547660_839829468 = ((NI) 0); { while (1) { TY177507 LOC19; NimStringDesc* LOC20; if (!(res_547660_839829468 <= HEX3Atmp_547657_839829468)) goto LA8; i_547649_839829468 = res_547660_839829468; { if (!(i_547649_839829468 < (NI)(size0 - ((NI) 1)))) goto LA11; { if (!(((NI) ((NI)((NI)(i_547649_839829468 + ((NI) 1)) % ((NI) 8)))) == ((NI) 0))) goto LA15; frmt0 = copyString(((NimStringDesc*) &T839829468_274)); } goto LA13; LA15: ; { frmt0 = copyString(((NimStringDesc*) &T839829468_275)); } LA13: ; } goto LA9; LA11: ; { frmt0 = copyString(((NimStringDesc*) &T839829468_276)); } LA9: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (NimStringDesc*)0; LOC20 = nsuToHex(((NI64)(NU64)(NU8)(cs0->data[i_547649_839829468])), ((NI) 2)); LOC19[0] = rope_177277_2381377266(LOC20); addf_178205_2381377266(&result0, frmt0, LOC19, 1); res_547660_839829468 += ((NI) 1); } LA8: ; } } } goto LA1; LA3: ; { NI64 LOC22; LOC22 = (NI64)0; LOC22 = bitsettoword_547578_839829468(cs0, size0); result0 = intliteral_537270_839829468(LOC22); } LA1: ; return result0; } N_NIMCALL(void, appcg_530640_839829468)(Tcgen527027* m0, Tcfilesection527005 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) { Ropeobj177006* LOC1; LOC1 = (Ropeobj177006*)0; LOC1 = ropecg_530407_839829468(m0, frmt0, args0, args0Len0); add_177482_2381377266(&(*m0).s[(s0)- 0], LOC1); } N_NIMCALL(Ropeobj177006*, genconstseq_557371_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* t0) { Ropeobj177006* result0; Ropeobj177006* data0; TY177507 LOC1; NI LOC2; TY533235 LOC18; NI LOC19; TY530811 LOC20; result0 = (Ropeobj177006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = len_291081_850551059(n0); LOC1[0] = rope_177401_2381377266(((NI64) (LOC2))); data0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_277), LOC1, 1); { NI LOC5; LOC5 = (NI)0; LOC5 = len_291081_850551059(n0); if (!(((NI) 0) < LOC5)) goto LA6; add_177487_2381377266(&data0, ((NimStringDesc*) &T839829468_278)); { NI i_557395_839829468; NI HEX3Atmp_557411_839829468; NI LOC9; NI res_557414_839829468; i_557395_839829468 = (NI)0; HEX3Atmp_557411_839829468 = (NI)0; LOC9 = (NI)0; LOC9 = len_291081_850551059(n0); HEX3Atmp_557411_839829468 = (NI)(LOC9 - ((NI) 1)); res_557414_839829468 = ((NI) 0); { while (1) { Ropeobj177006* LOC17; if (!(res_557414_839829468 <= HEX3Atmp_557411_839829468)) goto LA11; i_557395_839829468 = res_557414_839829468; { TY531289 LOC16; if (!(((NI) 0) < i_557395_839829468)) goto LA14; memset((void*)LOC16, 0, sizeof(LOC16)); addf_178205_2381377266(&data0, ((NimStringDesc*) &T839829468_279), LOC16, 0); } LA14: ; LOC17 = (Ropeobj177006*)0; LOC17 = genconstexpr_552849_839829468(p0, (*n0).kindU.S6.sons->data[i_557395_839829468]); add_177482_2381377266(&data0, LOC17); res_557414_839829468 += ((NI) 1); } LA11: ; } } add_177487_2381377266(&data0, ((NimStringDesc*) &T839829468_280)); } LA6: ; add_177487_2381377266(&data0, ((NimStringDesc*) &T839829468_280)); result0 = gettempname_531598_839829468((*p0).module); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = gettypedesc_533673_839829468((*p0).module, (*t0).sons->data[((NI) 0)]); LOC19 = (NI)0; LOC19 = len_291081_850551059(n0); LOC18[1] = rope_177401_2381377266(((NI64) (LOC19))); LOC18[2] = result0; LOC18[3] = data0; appcg_530640_839829468((*p0).module, ((Tcfilesection527005) 8), ((NimStringDesc*) &T839829468_281), LOC18, 4); memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC20[1] = result0; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_282), LOC20, 2); return result0; } N_NIMCALL(Ropeobj177006*, gennamedconstexpr_557284_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { if (!((*n0).kind == ((Tnodekind290020) 34))) goto LA3; result0 = genconstexpr_552849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]); } goto LA1; LA3: ; { result0 = genconstexpr_552849_839829468(p0, n0); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, genconstsimplelist_557299_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; NI length0; TY531289 LOC10; result0 = (Ropeobj177006*)0; length0 = sonslen_293351_850551059(n0); result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_223)); { NI i_557333_839829468; NI HEX3Atmp_557362_839829468; NI HEX3Atmp_557363_839829468; NI res_557366_839829468; i_557333_839829468 = (NI)0; HEX3Atmp_557362_839829468 = (NI)0; HEX3Atmp_557363_839829468 = (NI)0; HEX3Atmp_557362_839829468 = ((*n0).kind == ((Tnodekind290020) 38)); HEX3Atmp_557363_839829468 = (NI)(length0 - ((NI) 2)); res_557366_839829468 = ((NI) (HEX3Atmp_557362_839829468)); { while (1) { TY177507 LOC4; if (!(res_557366_839829468 <= HEX3Atmp_557363_839829468)) goto LA3; i_557333_839829468 = res_557366_839829468; memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = gennamedconstexpr_557284_839829468(p0, (*n0).kindU.S6.sons->data[i_557333_839829468]); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_283), LOC4, 1); res_557366_839829468 += ((NI) 1); } LA3: ; } } { Ropeobj177006* LOC9; if (!(((NI) (((*n0).kind == ((Tnodekind290020) 38)))) < length0)) goto LA7; LOC9 = (Ropeobj177006*)0; LOC9 = gennamedconstexpr_557284_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))]); add_177482_2381377266(&result0, LOC9); } LA7: ; memset((void*)LOC10, 0, sizeof(LOC10)); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_160), LOC10, 0); return result0; } N_NIMCALL(Ropeobj177006*, genconstexpr_552849_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; switch ((*n0).kind) { case ((Tnodekind290020) 58): case ((Tnodekind290020) 59): { result0 = genconstexpr_552849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]); } break; case ((Tnodekind290020) 39): { Tbitset337004* cs0; NI64 LOC3; cs0 = (Tbitset337004*)0; tobitset_338001_452470228(n0, (&cs0)); LOC3 = (NI64)0; LOC3 = getsize_318135_3876443242((*n0).typ); result0 = genrawsetdata_547629_839829468(cs0, ((NI) (LOC3))); } break; case ((Tnodekind290020) 41): case ((Tnodekind290020) 37): case ((Tnodekind290020) 155): case ((Tnodekind290020) 38): { Ttype290840* t0; t0 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256)); { if (!((*t0).kind == ((Ttypekind290244) 24))) goto LA7; result0 = genconstseq_557371_839829468(p0, n0, t0); } goto LA5; LA7: ; { result0 = genconstsimplelist_557299_839829468(p0, n0); } LA5: ; } break; default: { Tloc290816 d0; memset((void*)(&d0), 0, sizeof(d0)); initlocexpr_537283_839829468(p0, n0, (&d0)); result0 = rdloc_536188_839829468((&d0)); } break; } return result0; } N_NIMCALL(void, requestconstimpl_537240_839829468)(Tcproc527021* p0, Tsym290834* sym0) { Tcgen527027* m0; Tcgen527027* q0; { m0 = (*p0).module; useheader_530369_839829468(m0, sym0); { Ropeobj177006* LOC5; if (!((*sym0).loc.k == ((Tlockind290808) 0))) goto LA3; LOC5 = (Ropeobj177006*)0; LOC5 = manglename_531205_839829468(sym0); fillloc_530282_839829468((&(*sym0).loc), ((Tlockind290808) 8), (*sym0).typ, LOC5, ((Tstorageloc290812) 1)); } LA3: ; { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA8; goto BeforeRet; } LA8: ; q0 = findpendingmodule_530241_839829468(m0, sym0); { NIM_BOOL LOC12; NIM_BOOL LOC14; TY533238 LOC17; LOC12 = (NIM_BOOL)0; LOC12 = !((q0 == NIM_NIL)); if (!(LOC12)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*sym0).Sup.id); LOC12 = !(LOC14); LA13: ; if (!LOC12) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_533673_839829468(q0, (*sym0).typ); LOC17[1] = (*sym0).loc.r; LOC17[2] = genconstexpr_552849_839829468((*q0).initproc, (*sym0).ast); addf_178205_2381377266(&(*q0).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3); } LA15: ; { NIM_BOOL LOC20; NIM_BOOL LOC22; Ropeobj177006* headerdecl0; TY530811 LOC25; LOC20 = (NIM_BOOL)0; LOC20 = !((q0 == m0)); if (!(LOC20)) goto LA21; LOC22 = (NIM_BOOL)0; LOC22 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LOC20 = !(LOC22); LA21: ; if (!LOC20) goto LA23; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = gettypedesc_533673_839829468(m0, (*sym0).loc.t); LOC25[1] = (*sym0).loc.r; headerdecl0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_284), LOC25, 2); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 8))- 0], headerdecl0); { NIM_BOOL LOC28; LOC28 = (NIM_BOOL)0; LOC28 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 6))&31U)))!=0); if (!(LOC28)) goto LA29; LOC28 = !((generatedheader_530201_839829468 == NIM_NIL)); LA29: ; if (!LOC28) goto LA30; add_177482_2381377266(&(*generatedheader_530201_839829468).s[(((Tcfilesection527005) 8))- 0], headerdecl0); } LA30: ; } LA23: ; }BeforeRet: ; } N_NIMCALL(void, gencomplexconst_556249_839829468)(Tcproc527021* p0, Tsym290834* sym0, Tloc290816* d0) { requestconstimpl_537240_839829468(p0, sym0); putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } static N_INLINE(Ropeobj177006**, procsec_527194_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0) { Ropeobj177006** result0; result0 = (Ropeobj177006**)0; result0 = &(*p0).blocks->data[((NI) 0)].sections[(s0)- 0]; return result0; } N_NIMCALL(void, accessthreadlocalvar_530945_839829468)(Tcproc527021* p0, Tsym290834* s0) { { NIM_BOOL LOC3; Ropeobj177006** LOC7; TY531289 LOC8; Ropeobj177006** LOC9; TY531289 LOC10; Ropeobj177006* LOC11; LOC3 = (NIM_BOOL)0; LOC3 = emulatedthreadvars_530949_839829468(); if (!(LOC3)) goto LA4; LOC3 = !((*p0).threadvaraccessed); LA4: ; if (!LOC3) goto LA5; (*p0).threadvaraccessed = NIM_TRUE; (*(*p0).module).flags |= ((NU8)1)<<((((Codegenflag527025) 1))%(sizeof(NU8)*8)); LOC7 = (Ropeobj177006**)0; LOC7 = procsec_527194_3723162438(p0, ((Tcprocsection527011) 0)); memset((void*)LOC8, 0, sizeof(LOC8)); addf_178205_2381377266(LOC7, ((NimStringDesc*) &T839829468_286), LOC8, 0); LOC9 = (Ropeobj177006**)0; LOC9 = procsec_527194_3723162438(p0, ((Tcprocsection527011) 1)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC11 = (Ropeobj177006*)0; LOC11 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_287), LOC10, 0); add_177482_2381377266(LOC9, LOC11); } LA5: ; } static N_INLINE(NIM_BOOL, isemptytype_295441_850551059)(Ttype290840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = (t0 == NIM_NIL); if (LOC1) goto LA2; LOC1 = ((IL64(4611686018427388032) &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, putdataintodest_548436_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0) { Tloc290816 a0; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3; initloc_530273_839829468((&a0), ((Tlockind290808) 8), t0, ((Tstorageloc290812) 1)); a0.r = r0; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag290810) 2))&15U)))!=0)) goto LA7; genassignment_537264_839829468(p0, (&(*d0)), (&a0), 0); } goto LA5; LA7: ; { genassignment_537264_839829468(p0, (&(*d0)), (&a0), 1); } LA5: ; } goto LA1; LA3: ; { (*d0).k = ((Tlockind290808) 8); unsureAsgnRef((void**) (&(*d0).t), t0); unsureAsgnRef((void**) (&(*d0).r), r0); } LA1: ; } N_NIMCALL(NIM_BOOL, freshlineinfo_530818_839829468)(Tcproc527021* p0, Tlineinfo189336 info0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*p0).lastlineinfo.line == info0.line)); if (LOC3) goto LA4; LOC3 = !(((*p0).lastlineinfo.fileindex == info0.fileindex)); LA4: ; if (!LOC3) goto LA5; (*p0).lastlineinfo.line = info0.line; (*p0).lastlineinfo.fileindex = info0.fileindex; result0 = NIM_TRUE; } LA5: ; return result0; } N_NIMCALL(void, genlinedir_530823_839829468)(Tcproc527021* p0, Tnode290802* t0) { NI line0; Ropeobj177006** LOC11; NimStringDesc* LOC12; line0 = safelinenm_530721_839829468((*t0).info); { Ropeobj177006** LOC5; TY531289 LOC6; Ropeobj177006* LOC7; Ropeobj177006* LOC8; Ropeobj177006* LOC9; Ropeobj177006* LOC10; if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 28))&63U)))!=0)) goto LA3; LOC5 = (Ropeobj177006**)0; LOC5 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); memset((void*)LOC6, 0, sizeof(LOC6)); LOC7 = (Ropeobj177006*)0; LOC7 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_293), LOC6, 0); LOC8 = (Ropeobj177006*)0; LOC8 = sourceline_190065_155036129((*t0).info); LOC9 = (Ropeobj177006*)0; LOC9 = HEX26_177418_2381377266(LOC7, LOC8); LOC10 = (Ropeobj177006*)0; LOC10 = HEX26_177418_2381377266(LOC9, rnl_177903_2381377266); add_177482_2381377266(LOC5, LOC10); } LA3: ; LOC11 = (Ropeobj177006**)0; LOC11 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); LOC12 = (NimStringDesc*)0; LOC12 = tofullpath_190261_155036129((*t0).info.fileindex); genclinedir_530725_839829468(LOC11, LOC12, line0); { NIM_BOOL LOC15; NIM_BOOL LOC17; LOC15 = (NIM_BOOL)0; LOC15 = ((163840 & (*p0).options) == 163840); if (!(LOC15)) goto LA16; LOC17 = (NIM_BOOL)0; LOC17 = ((*p0).prc == NIM_NIL); if (LOC17) goto LA18; LOC17 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)); LA18: ; LOC15 = LOC17; LA16: ; if (!LOC15) goto LA19; { NIM_BOOL LOC23; TY530811 LOC26; NimStringDesc* LOC27; LOC23 = (NIM_BOOL)0; LOC23 = freshlineinfo_530818_839829468(p0, (*t0).info); if (!LOC23) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rope_177401_2381377266(((NI64) (line0))); LOC27 = (NimStringDesc*)0; LOC27 = tofilename_190257_155036129((*t0).info.fileindex); LOC26[1] = makecstring_189638_155036129(LOC27); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_294), LOC26, 2); } LA24: ; } goto LA13; LA19: ; { NIM_BOOL LOC29; NIM_BOOL LOC30; NIM_BOOL LOC32; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((98304 & (*p0).options) == 98304); if (!(LOC30)) goto LA31; LOC32 = (NIM_BOOL)0; LOC32 = ((*p0).prc == NIM_NIL); if (LOC32) goto LA33; LOC32 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)); LA33: ; LOC30 = LOC32; LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA34; LOC29 = (((NI32) 0) <= (*t0).info.fileindex); LA34: ; if (!LOC29) goto LA35; { NIM_BOOL LOC39; TY530811 LOC42; LOC39 = (NIM_BOOL)0; LOC39 = freshlineinfo_530818_839829468(p0, (*t0).info); if (!LOC39) goto LA40; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = rope_177401_2381377266(((NI64) (line0))); LOC42[1] = quotedfilename_194818_155036129((*t0).info); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_295), LOC42, 2); } LA40: ; } goto LA13; LA35: ; LA13: ; } N_NIMCALL(Ropeobj177006*, getlabel_537217_839829468)(Tcproc527021* p0) { Ropeobj177006* result0; Ropeobj177006* LOC1; result0 = (Ropeobj177006*)0; (*p0).labels += ((NI) 1); LOC1 = (Ropeobj177006*)0; LOC1 = rope_177401_2381377266(((NI64) ((*p0).labels))); result0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC1); return result0; } N_NIMCALL(void, fixlabel_537230_839829468)(Tcproc527021* p0, Ropeobj177006* labl0) { TY177507 LOC1; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = labl0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_299), LOC1, 1); } N_NIMCALL(void, genandor_552311_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) { Ropeobj177006* L0; Tloc290816 tmp0; L0 = (Ropeobj177006*)0; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_535032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE); (*p0).splitdecls += ((NI) 1); expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); L0 = getlabel_537217_839829468(p0); { TY530811 LOC5; if (!(m0 == ((Tmagic290524) 127))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&tmp0)); LOC5[1] = L0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_297), LOC5, 2); } goto LA1; LA3: ; { TY530811 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_536188_839829468((&tmp0)); LOC7[1] = L0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_298), LOC7, 2); } LA1: ; expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&tmp0)); fixlabel_537230_839829468(p0, L0); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA10; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI290816)); } goto LA8; LA10: ; { genassignment_537264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA8: ; (*p0).splitdecls -= ((NI) 1); } N_NIMCALL(void, unaryarith_550646_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) { Tloc290816 a0; Ttype290840* t0; TY533238 LOC1; NI64 LOC2; Ropeobj177006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); t0 = (Ttype290840*)0; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); LOC2 = (NI64)0; LOC2 = getsize_318135_3876443242(t0); LOC1[1] = rope_177401_2381377266((NI64)(LOC2 * IL64(8))); LOC1[2] = getsimpletypedesc_531936_839829468((*p0).module, (*e0).typ); LOC3 = (Ropeobj177006*)0; LOC3 = HEX25_177905_2381377266(unarithtab_550653_839829468[(op0)- 99], LOC1, 3); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC3, ((Tstorageloc290812) 0)); } N_NIMCALL(void, unaryarithoverflow_549633_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) { Tloc290816 a0; Ttype290840* t0; TY530811 LOC7; NI64 LOC8; Ropeobj177006* LOC9; memset((void*)(&a0), 0, sizeof(a0)); t0 = (Ttype290840*)0; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832)); { TY530811 LOC5; NI64 LOC6; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&a0)); LOC6 = (NI64)0; LOC6 = firstord_318001_3876443242(t0); LOC5[1] = intliteral_537270_839829468(LOC6); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_317), LOC5, 2); } LA3: ; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_536188_839829468((&a0)); LOC8 = (NI64)0; LOC8 = getsize_318135_3876443242(t0); LOC7[1] = rope_177401_2381377266((NI64)(LOC8 * IL64(8))); LOC9 = (Ropeobj177006*)0; LOC9 = HEX25_177905_2381377266(opr_549640_839829468[(m0)- 96], LOC7, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC9, ((Tstorageloc290812) 0)); } N_NIMCALL(void, binaryarith_549819_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) { Tloc290816 a0; Tloc290816 b0; NI64 s0; NI64 LOC1; NI64 LOC2; TY533235 LOC3; Ropeobj177006* LOC4; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); s0 = (NI64)0; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); LOC1 = (NI64)0; LOC1 = getsize_318135_3876443242(a0.t); LOC2 = (NI64)0; LOC2 = getsize_318135_3876443242(b0.t); s0 = (NI64)(((LOC1 >= LOC2) ? LOC1 : LOC2) * IL64(8)); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = rdloc_536188_839829468((&a0)); LOC3[1] = rdloc_536188_839829468((&b0)); LOC3[2] = rope_177401_2381377266(s0); LOC3[3] = getsimpletypedesc_531936_839829468((*p0).module, (*e0).typ); LOC4 = (Ropeobj177006*)0; LOC4 = HEX25_177905_2381377266(binarithtab_549826_839829468[(op0)- 52], LOC3, 4); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC4, ((Tstorageloc290812) 0)); } N_NIMCALL(void, binaryfloatarith_554729_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) { { Tloc290816 a0; Tloc290816 b0; TY533235 LOC5; Tnode290802* LOC6; Ropeobj177006* LOC7; if (!!(((384 & (*p0).options) == 0))) goto LA3; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_177277_2381377266(opr_554763_839829468[(m0)- 52]); LOC5[1] = rdloc_536188_839829468((&a0)); LOC5[2] = rdloc_536188_839829468((&b0)); LOC6 = (Tnode290802*)0; LOC6 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1)); LOC5[3] = getsimpletypedesc_531936_839829468((*p0).module, (*LOC6).typ); LOC7 = (Ropeobj177006*)0; LOC7 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_319), LOC5, 4); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc290812) 0)); { TY177507 LOC12; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 7))&31U)))!=0)) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_536188_839829468((&(*d0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_323), LOC12, 1); } LA10: ; { TY177507 LOC17; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 8))&31U)))!=0)) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_536188_839829468((&(*d0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_324), LOC17, 1); } LA15: ; } goto LA1; LA3: ; { binaryarith_549819_839829468(p0, e0, d0, m0); } LA1: ; } N_NIMCALL(void, geneqproc_550214_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { Ttype290840* LOC3; TY530811 LOC6; Ropeobj177006* LOC7; LOC3 = (Ttype290840*)0; LOC3 = skiptypes_294099_850551059(a0.t, IL64(211106232576256)); if (!((*LOC3).callconv == ((Tcallingconvention290002) 8))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rdloc_536188_839829468((&a0)); LOC6[1] = rdloc_536188_839829468((&b0)); LOC7 = (Ropeobj177006*)0; LOC7 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_352), LOC6, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc290812) 0)); } goto LA1; LA4: ; { TY530811 LOC9; Ropeobj177006* LOC10; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = rdloc_536188_839829468((&a0)); LOC9[1] = rdloc_536188_839829468((&b0)); LOC10 = (Ropeobj177006*)0; LOC10 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_341), LOC9, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC10, ((Tstorageloc290812) 0)); } LA1: ; } N_NIMCALL(Ropeobj177006*, rdcharloc_536227_839829468)(Tloc290816* a0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = rdloc_536188_839829468(a0); { Ttype290840* LOC3; TY177507 LOC6; LOC3 = (Ttype290840*)0; LOC3 = skiptypes_294099_850551059((*a0).t, IL64(211106233624832)); if (!((*LOC3).kind == ((Ttypekind290244) 2))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = result0; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_358), LOC6, 1); } LA4: ; return result0; } N_NIMCALL(Ropeobj177006*, binaryarithoverflowraw_549235_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816* a0, Tloc290816* b0, NimStringDesc* frmt0) { Ropeobj177006* result0; NI64 size0; Ropeobj177006* storage0; TY530811 LOC6; TY533238 LOC7; result0 = (Ropeobj177006*)0; size0 = getsize_318135_3876443242(t0); { if (!(size0 < ((NI64) (intsize_175641_4151366050)))) goto LA3; storage0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_36)); } goto LA1; LA3: ; { storage0 = gettypedesc_533673_839829468((*p0).module, t0); } LA1: ; result0 = gettempname_531598_839829468((*p0).module); memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = storage0; LOC6[1] = result0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_54), LOC6, 2); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = result0; LOC7[1] = rdcharloc_536227_839829468(a0); LOC7[2] = rdcharloc_536227_839829468(b0); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC7, 3); { NIM_BOOL LOC10; TY533238 LOC14; NI64 LOC15; NI64 LOC16; LOC10 = (NIM_BOOL)0; LOC10 = (size0 < ((NI64) (intsize_175641_4151366050))); if (LOC10) goto LA11; LOC10 = ((1064960 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); LA11: ; if (!LOC10) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = result0; LOC15 = (NI64)0; LOC15 = firstord_318001_3876443242(t0); LOC14[1] = intliteral_537270_839829468(LOC15); LOC16 = (NI64)0; LOC16 = lastord_318004_3876443242(t0); LOC14[2] = intliteral_537270_839829468(LOC16); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_359), LOC14, 3); } LA12: ; return result0; } N_NIMCALL(void, binaryarithoverflow_549262_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) { Tloc290816 a0; Tloc290816 b0; Ttype290840* t0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832)); { Ropeobj177006* res0; TY533238 LOC5; if (!!((((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC5[1] = rdloc_536188_839829468((&a0)); LOC5[2] = rdloc_536188_839829468((&b0)); res0 = HEX25_177905_2381377266(opr_549279_839829468[(m0)- 45], LOC5, 3); putintodest_548468_839829468(p0, d0, (*e0).typ, res0, ((Tstorageloc290812) 0)); } goto LA1; LA3: ; { Ropeobj177006* res0; NimStringDesc* LOC7; TY530811 LOC13; Ropeobj177006* LOC14; LOC7 = (NimStringDesc*)0; { if (!((*t0).kind == ((Ttypekind290244) 35))) goto LA10; LOC7 = copyString(prc64_549274_839829468[(m0)- 45]); } goto LA8; LA10: ; { LOC7 = copyString(prc_549269_839829468[(m0)- 45]); } LA8: ; res0 = binaryarithoverflowraw_549235_839829468(p0, t0, (&a0), (&b0), LOC7); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC13[1] = res0; LOC14 = (Ropeobj177006*)0; LOC14 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_370), LOC13, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC14, ((Tstorageloc290812) 0)); } LA1: ; } N_NIMCALL(Ropeobj177006*, lenfield_537305_839829468)(Tcproc527021* p0) { Ropeobj177006* result0; NimStringDesc* LOC1; result0 = (Ropeobj177006*)0; LOC1 = (NimStringDesc*)0; { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC4) goto LA5; LOC4 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA5: ; if (!LOC4) goto LA6; LOC1 = copyString(((NimStringDesc*) &T839829468_157)); } goto LA2; LA6: ; { LOC1 = copyString(((NimStringDesc*) &T839829468_158)); } LA2: ; result0 = rope_177277_2381377266(LOC1); return result0; } N_NIMCALL(void, gcusage_552439_839829468)(Tnode290802* n0) { { NimStringDesc* LOC5; if (!(gselectedgc_168133_2607990831 == ((Tgcmode168080) 0))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = rendertree_309044_382274130(n0, 0); message_194095_155036129((*n0).info, ((Tmsgkind189002) 263), LOC5); } LA3: ; } N_NIMCALL(void, genrepr_553339_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* t0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); switch ((*t0).kind) { case ((Ttypekind290244) 31) ... ((Ttypekind290244) 35): case ((Ttypekind290244) 40) ... ((Ttypekind290244) 44): { TY177507 LOC2; Ropeobj177006* LOC3; memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_536188_839829468((&a0)); LOC3 = (Ropeobj177006*)0; LOC3 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_371), LOC2, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC3, a0.s); } break; case ((Ttypekind290244) 36) ... ((Ttypekind290244) 39): { TY177507 LOC5; Ropeobj177006* LOC6; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&a0)); LOC6 = (Ropeobj177006*)0; LOC6 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_372), LOC5, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC6, a0.s); } break; case ((Ttypekind290244) 1): { TY177507 LOC8; Ropeobj177006* LOC9; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_536188_839829468((&a0)); LOC9 = (Ropeobj177006*)0; LOC9 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_373), LOC8, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC9, a0.s); } break; case ((Ttypekind290244) 2): { TY177507 LOC11; Ropeobj177006* LOC12; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdloc_536188_839829468((&a0)); LOC12 = (Ropeobj177006*)0; LOC12 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_374), LOC11, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC12, a0.s); } break; case ((Ttypekind290244) 14): case ((Ttypekind290244) 15): { TY530811 LOC14; Ropeobj177006* LOC15; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_536188_839829468((&a0)); LOC14[1] = gentypeinfo_533941_839829468((*p0).module, t0); LOC15 = (Ropeobj177006*)0; LOC15 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_375), LOC14, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC15, a0.s); } break; case ((Ttypekind290244) 28): { TY177507 LOC17; Ropeobj177006* LOC18; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_536188_839829468((&a0)); LOC18 = (Ropeobj177006*)0; LOC18 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_376), LOC17, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC18, a0.s); } break; case ((Ttypekind290244) 19): { TY530811 LOC20; Ropeobj177006* LOC21; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = addrloc_536204_839829468((&a0)); LOC20[1] = gentypeinfo_533941_839829468((*p0).module, t0); LOC21 = (Ropeobj177006*)0; LOC21 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_377), LOC20, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC21, a0.s); } break; case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { Tloc290816 b0; TY530811 LOC34; Ttype290840* LOC35; Ropeobj177006* LOC36; memset((void*)(&b0), 0, sizeof(b0)); switch ((*a0.t).kind) { case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { TY177507 LOC24; Ropeobj177006* LOC25; memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = rdloc_536188_839829468((&a0)); LOC25 = (Ropeobj177006*)0; LOC25 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_378), LOC24, 1); putintodest_548468_839829468(p0, (&b0), (*e0).typ, LOC25, a0.s); } break; case ((Ttypekind290244) 28): case ((Ttypekind290244) 24): { TY530811 LOC27; Ropeobj177006* LOC28; memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = rdloc_536188_839829468((&a0)); LOC27[1] = lenfield_537305_839829468(p0); LOC28 = (Ropeobj177006*)0; LOC28 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_379), LOC27, 2); putintodest_548468_839829468(p0, (&b0), (*e0).typ, LOC28, a0.s); } break; case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { TY530811 LOC30; NI64 LOC31; Ropeobj177006* LOC32; memset((void*)LOC30, 0, sizeof(LOC30)); LOC30[0] = rdloc_536188_839829468((&a0)); LOC31 = (NI64)0; LOC31 = lengthord_318007_3876443242(a0.t); LOC30[1] = rope_177401_2381377266(LOC31); LOC32 = (Ropeobj177006*)0; LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_380), LOC30, 2); putintodest_548468_839829468(p0, (&b0), (*e0).typ, LOC32, a0.s); } break; default: { internalerror_194100_155036129((*(*e0).kindU.S6.sons->data[((NI) 0)]).info, ((NimStringDesc*) &T839829468_381)); } break; } memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = rdloc_536188_839829468((&b0)); LOC35 = (Ttype290840*)0; LOC35 = elemtype_318394_3876443242(t0); LOC34[1] = gentypeinfo_533941_839829468((*p0).module, LOC35); LOC36 = (Ropeobj177006*)0; LOC36 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_382), LOC34, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC36, a0.s); } break; case ((Ttypekind290244) 29): case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): case ((Ttypekind290244) 22): case ((Ttypekind290244) 21): case ((Ttypekind290244) 26): case ((Ttypekind290244) 5): case ((Ttypekind290244) 24): { TY530811 LOC38; Ropeobj177006* LOC39; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = rdloc_536188_839829468((&a0)); LOC38[1] = gentypeinfo_533941_839829468((*p0).module, t0); LOC39 = (Ropeobj177006*)0; LOC39 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC38, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC39, a0.s); } break; case ((Ttypekind290244) 3): case ((Ttypekind290244) 62): { localerror_194085_155036129((*e0).info, ((NimStringDesc*) &T839829468_384)); } break; default: { TY530811 LOC42; Ropeobj177006* LOC43; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = addrloc_536204_839829468((&a0)); LOC42[1] = gentypeinfo_533941_839829468((*p0).module, t0); LOC43 = (Ropeobj177006*)0; LOC43 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC42, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC43, a0.s); } break; } gcusage_552439_839829468(e0); } N_NIMCALL(void, gengettypeinfo_553383_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Ttype290840* t0; Ropeobj177006* LOC1; t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); LOC1 = (Ropeobj177006*)0; LOC1 = gentypeinfo_533941_839829468((*p0).module, t0); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC1, ((Tstorageloc290812) 0)); } N_NIMCALL(void, genswap_553638_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Tloc290816 tmp0; Ttype290840* LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); LOC1 = (Ttype290840*)0; LOC1 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); gettemp_535032_839829468(p0, LOC1, (&tmp0), NIM_FALSE); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); genassignment_537264_839829468(p0, (&tmp0), (&a0), 0); genassignment_537264_839829468(p0, (&a0), (&b0), 0); genassignment_537264_839829468(p0, (&b0), (&tmp0), 0); } N_NIMCALL(void, unaryexpr_549209_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; TY177507 LOC1; Ropeobj177006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0)); } N_NIMCALL(void, binarystmt_548501_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; Tloc290816 b0; TY530811 LOC5; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); { if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3; internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_387)); } LA3: ; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&a0)); LOC5[1] = rdloc_536188_839829468((&b0)); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC5, 2); } N_NIMCALL(void, genstrconcat_552452_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 tmp0; NI L0; Ropeobj177006* appends0; Ropeobj177006* lens0; TY533238 LOC21; Ropeobj177006** LOC22; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_535032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE); L0 = ((NI) 0); appends0 = NIM_NIL; lens0 = NIM_NIL; { NI i_552475_839829468; NI HEX3Atmp_552547_839829468; NI LOC2; NI res_552550_839829468; i_552475_839829468 = (NI)0; HEX3Atmp_552547_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(e0); HEX3Atmp_552547_839829468 = (NI)(LOC2 - ((NI) 2)); res_552550_839829468 = ((NI) 0); { while (1) { if (!(res_552550_839829468 <= HEX3Atmp_552547_839829468)) goto LA4; i_552475_839829468 = res_552550_839829468; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))], (&a0)); { Ttype290840* LOC7; TY530811 LOC10; Ropeobj177006* LOC11; LOC7 = (Ttype290840*)0; LOC7 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).typ, IL64(211106242013440)); if (!((*LOC7).kind == ((Ttypekind290244) 2))) goto LA8; L0 += ((NI) 1); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0.r; LOC10[1] = rdloc_536188_839829468((&a0)); LOC11 = (Ropeobj177006*)0; LOC11 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2); add_177482_2381377266(&appends0, LOC11); } goto LA5; LA8: ; { TY530811 LOC19; Ropeobj177006* LOC20; { if (!((*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kind >= ((Tnodekind290020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kind <= ((Tnodekind290020) 22))) goto LA15; L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kindU.S3.strval->Sup.len : 0); } goto LA13; LA15: ; { TY530811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_536188_839829468((&a0)); LOC18[1] = lenfield_537305_839829468(p0); addf_178205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2); } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = tmp0.r; LOC19[1] = rdloc_536188_839829468((&a0)); LOC20 = (Ropeobj177006*)0; LOC20 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2); add_177482_2381377266(&appends0, LOC20); } LA5: ; res_552550_839829468 += ((NI) 1); } LA4: ; } } memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = tmp0.r; LOC21[1] = lens0; LOC21[2] = rope_177401_2381377266(((NI64) (L0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_393), LOC21, 3); LOC22 = (Ropeobj177006**)0; LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(LOC22, appends0); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA25; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI290816)); } goto LA23; LA25: ; { genassignment_537264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA23: ; gcusage_552439_839829468(e0); } N_NIMCALL(void, genstrappend_552554_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 dest0; Ropeobj177006* appends0; Ropeobj177006* lens0; NI L0; TY533238 LOC21; Ropeobj177006** LOC22; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&dest0), 0, sizeof(dest0)); appends0 = (Ropeobj177006*)0; lens0 = (Ropeobj177006*)0; L0 = ((NI) 0); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&dest0)); { NI i_552615_839829468; NI HEX3Atmp_552676_839829468; NI LOC2; NI res_552679_839829468; i_552615_839829468 = (NI)0; HEX3Atmp_552676_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(e0); HEX3Atmp_552676_839829468 = (NI)(LOC2 - ((NI) 3)); res_552679_839829468 = ((NI) 0); { while (1) { if (!(res_552679_839829468 <= HEX3Atmp_552676_839829468)) goto LA4; i_552615_839829468 = res_552679_839829468; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))], (&a0)); { Ttype290840* LOC7; TY530811 LOC10; Ropeobj177006* LOC11; LOC7 = (Ttype290840*)0; LOC7 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).typ, IL64(211106242013440)); if (!((*LOC7).kind == ((Ttypekind290244) 2))) goto LA8; L0 += ((NI) 1); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_536188_839829468((&dest0)); LOC10[1] = rdloc_536188_839829468((&a0)); LOC11 = (Ropeobj177006*)0; LOC11 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2); add_177482_2381377266(&appends0, LOC11); } goto LA5; LA8: ; { TY530811 LOC19; Ropeobj177006* LOC20; { if (!((*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kind >= ((Tnodekind290020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kind <= ((Tnodekind290020) 22))) goto LA15; L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kindU.S3.strval->Sup.len : 0); } goto LA13; LA15: ; { TY530811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_536188_839829468((&a0)); LOC18[1] = lenfield_537305_839829468(p0); addf_178205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2); } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_536188_839829468((&dest0)); LOC19[1] = rdloc_536188_839829468((&a0)); LOC20 = (Ropeobj177006*)0; LOC20 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2); add_177482_2381377266(&appends0, LOC20); } LA5: ; res_552679_839829468 += ((NI) 1); } LA4: ; } } memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdloc_536188_839829468((&dest0)); LOC21[1] = lens0; LOC21[2] = rope_177401_2381377266(((NI64) (L0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_395), LOC21, 3); LOC22 = (Ropeobj177006**)0; LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(LOC22, appends0); gcusage_552439_839829468(e0); } N_NIMCALL(void, genseqelemappend_552683_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { NimStringDesc* seqappendpattern0; Tloc290816 a0; Tloc290816 b0; Tloc290816 dest0; Ttype290840* bt0; TY533238 LOC8; Ttype290840* LOC9; TY530811 LOC10; TY530811 LOC11; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_396)); } goto LA1; LA5: ; { seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_397)); } LA1: ; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&dest0), 0, sizeof(dest0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); bt0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 2)]).typ, IL64(211106240964864)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_536188_839829468((&a0)); LOC9 = (Ttype290840*)0; LOC9 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC8[1] = gettypedesc_533673_839829468((*p0).module, LOC9); LOC8[2] = gettypedesc_533673_839829468((*p0).module, bt0); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), seqappendpattern0, LOC8, 3); initloc_530273_839829468((&dest0), ((Tlockind290808) 6), bt0, ((Tstorageloc290812) 3)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_536188_839829468((&a0)); LOC10[1] = lenfield_537305_839829468(p0); dest0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_398), LOC10, 2); genassignment_537264_839829468(p0, (&dest0), (&b0), 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdloc_536188_839829468((&a0)); LOC11[1] = lenfield_537305_839829468(p0); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_399), LOC11, 2); gcusage_552439_839829468(e0); } N_NIMCALL(void, binaryexpr_548549_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; Tloc290816 b0; TY530811 LOC1; Ropeobj177006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); LOC1[1] = rdloc_536188_839829468((&b0)); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0)); } N_NIMCALL(void, genstrequals_554667_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 x0; Tnode290802* a0; Tnode290802* b0; memset((void*)(&x0), 0, sizeof(x0)); a0 = (*e0).kindU.S6.sons->data[((NI) 1)]; b0 = (*e0).kindU.S6.sons->data[((NI) 2)]; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*a0).kind == ((Tnodekind290020) 23)); if (LOC3) goto LA4; LOC3 = ((*b0).kind == ((Tnodekind290020) 23)); LA4: ; if (!LOC3) goto LA5; binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341)); } goto LA1; LA5: ; { NIM_BOOL LOC8; TY530811 LOC12; Ropeobj177006* LOC13; LOC8 = (NIM_BOOL)0; LOC8 = ((*a0).kind >= ((Tnodekind290020) 20) && (*a0).kind <= ((Tnodekind290020) 22)); if (!(LOC8)) goto LA9; LOC8 = (((*a0).kindU.S3.strval) && ((*a0).kindU.S3.strval)->Sup.len == 0); LA9: ; if (!LOC8) goto LA10; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&x0)); memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_536188_839829468((&x0)); LOC12[1] = lenfield_537305_839829468(p0); LOC13 = (Ropeobj177006*)0; LOC13 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC12, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC13, ((Tstorageloc290812) 0)); } goto LA1; LA10: ; { NIM_BOOL LOC15; TY530811 LOC19; Ropeobj177006* LOC20; LOC15 = (NIM_BOOL)0; LOC15 = ((*b0).kind >= ((Tnodekind290020) 20) && (*b0).kind <= ((Tnodekind290020) 22)); if (!(LOC15)) goto LA16; LOC15 = (((*b0).kindU.S3.strval) && ((*b0).kindU.S3.strval)->Sup.len == 0); LA16: ; if (!LOC15) goto LA17; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&x0)); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_536188_839829468((&x0)); LOC19[1] = lenfield_537305_839829468(p0); LOC20 = (Ropeobj177006*)0; LOC20 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC19, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC20, ((Tstorageloc290812) 0)); } goto LA1; LA17: ; { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_401)); } LA1: ; } N_NIMCALL(void, genisnil_550620_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Ttype290840* t0; t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind290244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention290002) 8)); LA4: ; if (!LOC3) goto LA5; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_404)); } goto LA1; LA5: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_405)); } LA1: ; } N_NIMCALL(void, gendollar_553391_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; TY177507 LOC1; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); a0.r = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 1); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA4; gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA4: ; genassignment_537264_839829468(p0, (&(*d0)), (&a0), 0); gcusage_552439_839829468(n0); } N_NIMCALL(Ropeobj177006*, genofhelper_553140_839829468)(Tcproc527021* p0, Ttype290840* dest0, Ropeobj177006* a0) { Ropeobj177006* result0; Ropeobj177006* ti0; result0 = (Ropeobj177006*)0; ti0 = gentypeinfo_533941_839829468((*p0).module, dest0); { NIM_BOOL LOC3; NIM_BOOL LOC5; TY530811 LOC9; LOC3 = (NIM_BOOL)0; LOC3 = (((*dest0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = (((*(*p0).module).flags &(1U<<((NU)(((Codegenflag527025) 5))&7U)))!=0); if (!(LOC5)) goto LA6; LOC5 = !((((*dest0).flags &(1U<<((NU)(((Ttypeflag290431) 5))&31U)))!=0)); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = a0; LOC9[1] = ti0; result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_414), LOC9, 2); } goto LA1; LA7: ; { Ropeobj177006* LOC11; Ropeobj177006* cache0; Ropeobj177006* LOC12; TY177507 LOC13; TY533238 LOC14; LOC11 = (Ropeobj177006*)0; LOC11 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_129)); (*(*p0).module).labels += ((NI) 1); LOC12 = (Ropeobj177006*)0; LOC12 = rope_177401_2381377266(((NI64) ((*(*p0).module).labels))); cache0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_415), LOC12); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = cache0; addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_416), LOC13, 1); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = a0; LOC14[1] = ti0; LOC14[2] = cache0; result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_417), LOC14, 3); } LA1: ; return result0; } N_NIMCALL(void, genof_553201_839829468)(Tcproc527021* p0, Tnode290802* x0, Ttype290840* typ0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* dest0; Ropeobj177006* r0; Ropeobj177006* nilcheck0; Ttype290840* t0; Ttype290840* LOC41; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, x0, (&a0)); dest0 = skiptypes_294099_850551059(typ0, IL64(211106247256320)); r0 = rdloc_536188_839829468((&a0)); nilcheck0 = NIM_NIL; t0 = skiptypes_294099_850551059(a0.t, IL64(211106232576256)); { while (1) { Ttype290840* LOC16; if (!((14680064 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)) goto LA2; { if (!!(((*t0).kind == ((Ttypekind290244) 23)))) goto LA5; nilcheck0 = r0; } LA5: ; { NIM_BOOL LOC9; NIM_BOOL LOC11; TY177507 LOC15; LOC9 = (NIM_BOOL)0; LOC9 = !(((*t0).kind == ((Ttypekind290244) 23))); if (LOC9) goto LA10; LOC11 = (NIM_BOOL)0; LOC11 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC11) goto LA12; LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA12: ; LOC9 = !(LOC11); LA10: ; if (!LOC9) goto LA13; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = r0; r0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC15, 1); } LA13: ; LOC16 = (Ttype290840*)0; LOC16 = lastson_293377_850551059(t0); t0 = skiptypes_294099_850551059(LOC16, IL64(211106232576256)); } LA2: ; } { NIM_BOOL LOC19; LOC19 = (NIM_BOOL)0; LOC19 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC19) goto LA20; LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA20: ; if (!!(LOC19)) goto LA21; { while (1) { NIM_BOOL LOC25; TY531289 LOC27; Ropeobj177006* LOC28; LOC25 = (NIM_BOOL)0; LOC25 = ((*t0).kind == ((Ttypekind290244) 17)); if (!(LOC25)) goto LA26; LOC25 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); LA26: ; if (!LOC25) goto LA24; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Ropeobj177006*)0; LOC28 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_153), LOC27, 0); add_177482_2381377266(&r0, LOC28); t0 = skiptypes_294099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360)); } LA24: ; } } LA21: ; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = isobjlackingtypefield_531515_839829468(t0); if (!LOC31) goto LA32; globalerror_194071_155036129((*x0).info, ((Tmsgkind189002) 4), ((NimStringDesc*) &T839829468_412)); } LA32: ; { TY530811 LOC38; if (!!((nilcheck0 == NIM_NIL))) goto LA36; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = nilcheck0; LOC38[1] = genofhelper_553140_839829468(p0, dest0, r0); r0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_413), LOC38, 2); } goto LA34; LA36: ; { TY177507 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = genofhelper_553140_839829468(p0, dest0, r0); r0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_418), LOC40, 1); } LA34: ; LOC41 = (Ttype290840*)0; LOC41 = getsystype_336150_3937434831(((Ttypekind290244) 1)); putintodest_548468_839829468(p0, d0, LOC41, r0, a0.s); } N_NIMCALL(void, genof_553331_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { genof_553201_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (*(*n0).kindU.S6.sons->data[((NI) 2)]).typ, d0); } N_NIMCALL(void, rawgennew_552741_839829468)(Tcproc527021* p0, Tloc290816* a0, Ropeobj177006* sizeexpr_552745_839829468) { Ropeobj177006* sizeexpr0; Ttype290840* reftype0; Tloc290816 b0; TY533238 args0; Ttype290840* bt0; sizeexpr0 = sizeexpr_552745_839829468; reftype0 = skiptypes_294099_850551059((*a0).t, IL64(211106242013440)); memset((void*)(&b0), 0, sizeof(b0)); initloc_530273_839829468((&b0), ((Tlockind290808) 6), (*a0).t, ((Tstorageloc290812) 3)); { TY177507 LOC5; Ttype290840* LOC6; if (!sizeexpr0 == 0) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (Ttype290840*)0; LOC6 = skiptypes_294099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832)); LOC5[0] = gettypedesc_533673_839829468((*p0).module, LOC6); sizeexpr0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_419), LOC5, 1); } LA3: ; memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_533673_839829468((*p0).module, reftype0); args0[1] = gentypeinfo_533941_839829468((*p0).module, reftype0); args0[2] = sizeexpr0; { NIM_BOOL LOC9; TY530811 LOC21; LOC9 = (NIM_BOOL)0; LOC9 = ((*a0).s == ((Tstorageloc290812) 3)); if (!(LOC9)) goto LA10; LOC9 = usesnativegc_168177_2607990831(); LA10: ; if (!LOC9) goto LA11; { NIM_BOOL LOC15; TY177507 LOC18; LOC15 = (NIM_BOOL)0; LOC15 = canformacycle_318123_3876443242((*a0).t); if (!LOC15) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_536188_839829468(a0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_420), LOC18, 1); } goto LA13; LA16: ; { TY177507 LOC20; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rdloc_536188_839829468(a0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_255), LOC20, 1); } LA13: ; b0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_421), args0, 3); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdloc_536188_839829468(a0); LOC21[1] = rdloc_536188_839829468((&b0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC21, 2); } goto LA7; LA11: ; { b0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_422), args0, 3); genassignment_537264_839829468(p0, a0, (&b0), 0); } LA7: ; bt0 = skiptypes_294099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832)); genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), bt0, a0, NIM_FALSE); } N_NIMCALL(void, gennew_552782_839829468)(Tcproc527021* p0, Tnode290802* e0) { Tloc290816 a0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); { NI LOC3; Tloc290816 se0; Ropeobj177006* LOC6; LOC3 = (NI)0; LOC3 = len_291081_850551059(e0); if (!(LOC3 == ((NI) 3))) goto LA4; memset((void*)(&se0), 0, sizeof(se0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&se0)); LOC6 = (Ropeobj177006*)0; LOC6 = rdloc_536188_839829468((&se0)); rawgennew_552741_839829468(p0, (&a0), LOC6); } goto LA1; LA4: ; { rawgennew_552741_839829468(p0, (&a0), NIM_NIL); } LA1: ; gcusage_552439_839829468(e0); } N_NIMCALL(void, gennewfinalize_553111_839829468)(Tcproc527021* p0, Tnode290802* e0) { Tloc290816 a0; Tloc290816 b0; Tloc290816 f0; Ttype290840* reftype0; Ttype290840* bt0; Ropeobj177006* ti0; TY530811 LOC1; TY533238 LOC2; Ttype290840* LOC3; Ttype290840* LOC4; Ttype290840* LOC5; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&f0), 0, sizeof(f0)); reftype0 = (Ttype290840*)0; bt0 = (Ttype290840*)0; ti0 = (Ropeobj177006*)0; reftype0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&f0)); initloc_530273_839829468((&b0), ((Tlockind290808) 6), a0.t, ((Tstorageloc290812) 3)); ti0 = gentypeinfo_533941_839829468((*p0).module, reftype0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = ti0; LOC1[1] = rdloc_536188_839829468((&f0)); addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_423), LOC1, 2); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = gettypedesc_533673_839829468((*p0).module, reftype0); LOC2[1] = ti0; LOC3 = (Ttype290840*)0; LOC3 = lastson_293377_850551059(reftype0); LOC4 = (Ttype290840*)0; LOC4 = skiptypes_294099_850551059(LOC3, IL64(211106233624832)); LOC2[2] = gettypedesc_533673_839829468((*p0).module, LOC4); b0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_424), LOC2, 3); genassignment_537264_839829468(p0, (&a0), (&b0), 0); LOC5 = (Ttype290840*)0; LOC5 = lastson_293377_850551059(reftype0); bt0 = skiptypes_294099_850551059(LOC5, IL64(211106233624832)); genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), bt0, (&a0), NIM_FALSE); gcusage_552439_839829468(e0); } N_NIMCALL(void, gennewseqaux_552795_839829468)(Tcproc527021* p0, Tloc290816* dest0, Ropeobj177006* length0) { Ttype290840* seqtype0; TY533238 args0; Tloc290816 call0; seqtype0 = skiptypes_294099_850551059((*dest0).t, IL64(211106242013440)); memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_533673_839829468((*p0).module, seqtype0); args0[1] = gentypeinfo_533941_839829468((*p0).module, seqtype0); args0[2] = length0; memset((void*)(&call0), 0, sizeof(call0)); initloc_530273_839829468((&call0), ((Tlockind290808) 6), (*dest0).t, ((Tstorageloc290812) 3)); { NIM_BOOL LOC3; TY530811 LOC15; LOC3 = (NIM_BOOL)0; LOC3 = ((*dest0).s == ((Tstorageloc290812) 3)); if (!(LOC3)) goto LA4; LOC3 = usesnativegc_168177_2607990831(); LA4: ; if (!LOC3) goto LA5; { NIM_BOOL LOC9; TY177507 LOC12; LOC9 = (NIM_BOOL)0; LOC9 = canformacycle_318123_3876443242((*dest0).t); if (!LOC9) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_536188_839829468(dest0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_420), LOC12, 1); } goto LA7; LA10: ; { TY177507 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_536188_839829468(dest0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_255), LOC14, 1); } LA7: ; call0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_425), args0, 3); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = rdloc_536188_839829468(dest0); LOC15[1] = rdloc_536188_839829468((&call0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC15, 2); } goto LA1; LA5: ; { call0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_426), args0, 3); genassignment_537264_839829468(p0, dest0, (&call0), 0); } LA1: ; } N_NIMCALL(void, gennewseq_552824_839829468)(Tcproc527021* p0, Tnode290802* e0) { Tloc290816 a0; Tloc290816 b0; Ropeobj177006* LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); LOC1 = (Ropeobj177006*)0; LOC1 = rdloc_536188_839829468((&b0)); gennewseqaux_552795_839829468(p0, (&a0), LOC1); gcusage_552439_839829468(e0); } N_NIMCALL(void, gennewseqofcap_552836_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Ttype290840* seqtype0; Tloc290816 a0; TY533238 LOC1; Ropeobj177006* LOC2; seqtype0 = skiptypes_294099_850551059((*e0).typ, IL64(211106242013440)); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = gettypedesc_533673_839829468((*p0).module, seqtype0); LOC1[1] = gentypeinfo_533941_839829468((*p0).module, seqtype0); LOC1[2] = rdloc_536188_839829468((&a0)); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_427), LOC1, 3); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0)); gcusage_552439_839829468(e0); } N_NIMCALL(Ropeobj177006*, getclosuretype_533685_839829468)(Tcgen527027* m0, Ttype290840* t0, Tclosuretypekind533681 kind0) { Ropeobj177006* result0; Intset266030 check0; Ropeobj177006* rettype0; Ropeobj177006* desc0; result0 = (Ropeobj177006*)0; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_266885_2627731572((&check0)); result0 = gettempname_531598_839829468(m0); rettype0 = (Ropeobj177006*)0; desc0 = (Ropeobj177006*)0; genprocparams_532115_839829468(m0, t0, &rettype0, &desc0, (&check0), !((kind0 == ((Tclosuretypekind533681) 0))), NIM_FALSE); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedtype_531451_839829468(t0); if (!!(LOC3)) goto LA4; { NIM_BOOL LOC8; TY533235 LOC12; LOC8 = (NIM_BOOL)0; LOC8 = !(((*t0).callconv == ((Tcallingconvention290002) 8))); if (LOC8) goto LA9; LOC8 = !((kind0 == ((Tclosuretypekind533681) 2))); LA9: ; if (!LOC8) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_177277_2381377266(Callingconvtostr_531587_839829468[((*t0).callconv)- 0]); LOC12[1] = rettype0; LOC12[2] = result0; LOC12[3] = desc0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC12, 4); } goto LA6; LA10: ; { TY533238 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = result0; LOC14[1] = rettype0; LOC14[2] = desc0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC14, 3); } LA6: ; } LA4: ; return result0; } N_NIMCALL(void, gensomecast_554481_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* etyp0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); etyp0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832)); { NIM_BOOL LOC3; TY530811 LOC7; Ropeobj177006* LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((IL64(281475111387152) &((NU64)1<<((NU)((*etyp0).kind)&63U)))!=0); if (!(LOC3)) goto LA4; LOC3 = !(((a0.flags &(1U<<((NU)(((Tlocflag290810) 0))&15U)))!=0)); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_533673_839829468((*p0).module, (*e0).typ); LOC7[1] = addrloc_536204_839829468((&a0)); LOC8 = (Ropeobj177006*)0; LOC8 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_429), LOC7, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC8, a0.s); } goto LA1; LA5: ; { NIM_BOOL LOC10; TY530811 LOC14; Ropeobj177006* LOC15; LOC10 = (NIM_BOOL)0; LOC10 = ((*etyp0).kind == ((Ttypekind290244) 25)); if (!(LOC10)) goto LA11; LOC10 = ((*etyp0).callconv == ((Tcallingconvention290002) 8)); LA11: ; if (!LOC10) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = getclosuretype_533685_839829468((*p0).module, etyp0, ((Tclosuretypekind533681) 1)); LOC14[1] = rdcharloc_536227_839829468((&a0)); LOC15 = (Ropeobj177006*)0; LOC15 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC14, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC15, a0.s); } goto LA1; LA12: ; { TY530811 LOC17; Ropeobj177006* LOC18; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_533673_839829468((*p0).module, (*e0).typ); LOC17[1] = rdcharloc_536227_839829468((&a0)); LOC18 = (Ropeobj177006*)0; LOC18 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC17, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC18, a0.s); } LA1: ; } N_NIMCALL(void, unaryexprchar_549222_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; TY177507 LOC1; Ropeobj177006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdcharloc_536227_839829468((&a0)); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0)); } N_NIMCALL(void, genord_554475_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { unaryexprchar_549222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_301)); } N_NIMCALL(void, genarraylen_553415_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) { Tnode290802* a0; Ttype290840* typ0; a0 = (*e0).kindU.S6.sons->data[((NI) 1)]; { if (!((*a0).kind == ((Tnodekind290020) 64))) goto LA3; a0 = (*a0).kindU.S6.sons->data[((NI) 0)]; } LA3: ; typ0 = skiptypes_294099_850551059((*a0).typ, IL64(211106240964864)); switch ((*typ0).kind) { case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { { if (!(op0 == ((Tmagic290524) 8))) goto LA8; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_431)); } goto LA6; LA8: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_432)); } LA6: ; } break; case ((Ttypekind290244) 29): { usestringh_530345_839829468((*p0).module); { if (!(op0 == ((Tmagic290524) 8))) goto LA14; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_433)); } goto LA12; LA14: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_434)); } LA12: ; } break; case ((Ttypekind290244) 28): case ((Ttypekind290244) 24): { { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC20) goto LA21; LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA21: ; if (!!(LOC20)) goto LA22; { if (!(op0 == ((Tmagic290524) 8))) goto LA26; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_435)); } goto LA24; LA26: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_436)); } LA24: ; } goto LA18; LA22: ; { { if (!(op0 == ((Tmagic290524) 8))) goto LA32; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_437)); } goto LA30; LA32: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_438)); } LA30: ; } LA18: ; } break; case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { { NI64 LOC40; Ropeobj177006* LOC41; if (!(op0 == ((Tmagic290524) 8))) goto LA38; LOC40 = (NI64)0; LOC40 = lastord_318004_3876443242(typ0); LOC41 = (Ropeobj177006*)0; LOC41 = rope_177401_2381377266(LOC40); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC41, ((Tstorageloc290812) 0)); } goto LA36; LA38: ; { NI64 LOC43; Ropeobj177006* LOC44; LOC43 = (NI64)0; LOC43 = lengthord_318007_3876443242(typ0); LOC44 = (Ropeobj177006*)0; LOC44 = rope_177401_2381377266(LOC43); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC44, ((Tstorageloc290812) 0)); } LA36: ; } break; default: { internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_439)); } break; } } N_NIMCALL(void, unarystmt_548527_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; TY177507 LOC5; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3; internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_442)); } LA3: ; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&a0)); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC5, 1); } N_NIMCALL(void, gensetlengthstr_553632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { binarystmt_548501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_445)); gcusage_552439_839829468(e0); } N_NIMCALL(void, gensetlengthseq_553500_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Ttype290840* t0; NimStringDesc* setlenpattern0; TY533235 LOC8; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; setlenpattern0 = copyString(((NimStringDesc*) &T839829468_446)); } goto LA1; LA5: ; { setlenpattern0 = copyString(((NimStringDesc*) &T839829468_447)); } LA1: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_536188_839829468((&a0)); LOC8[1] = rdloc_536188_839829468((&b0)); LOC8[2] = gettypedesc_533673_839829468((*p0).module, t0); LOC8[3] = gettypedesc_533673_839829468((*p0).module, (*t0).sons->data[((NI) 0)]); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), setlenpattern0, LOC8, 4); gcusage_552439_839829468(e0); } N_NIMCALL(Ropeobj177006*, rdsetelemloc_553662_839829468)(Tloc290816* a0, Ttype290840* settype0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = rdcharloc_536227_839829468(a0); { NI64 LOC3; TY530811 LOC6; NI64 LOC7; LOC3 = (NI64)0; LOC3 = firstord_318001_3876443242(settype0); if (!!((LOC3 == IL64(0)))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = result0; LOC7 = (NI64)0; LOC7 = firstord_318001_3876443242(settype0); LOC6[1] = rope_177401_2381377266(LOC7); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_448), LOC6, 2); } LA4: ; return result0; } N_NIMCALL(void, binarystmtinexcl_553858_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; Tloc290816 b0; TY530811 LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); LOC1[1] = rdsetelemloc_553662_839829468((&b0), a0.t); linef_530700_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC1, 2); } N_NIMCALL(void, binaryexprchar_548809_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) { Tloc290816 a0; Tloc290816 b0; TY530811 LOC1; Ropeobj177006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdcharloc_536227_839829468((&a0)); LOC1[1] = rdcharloc_536227_839829468((&b0)); LOC2 = (Ropeobj177006*)0; LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0)); } N_NIMCALL(NIM_BOOL, fewcmps_553803_839829468)(Tnode290802* s0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { if (!!(((*s0).kind == ((Tnodekind290020) 39)))) goto LA3; internalerror_194100_155036129((*s0).info, ((NimStringDesc*) &T839829468_463)); } LA3: ; { NIM_BOOL LOC7; NI64 LOC8; LOC7 = (NIM_BOOL)0; LOC8 = (NI64)0; LOC8 = getsize_318135_3876443242((*s0).typ); LOC7 = (LOC8 <= ((NI64) (intsize_175641_4151366050))); if (!(LOC7)) goto LA9; LOC7 = (((*s0).flags &(1U<<((NU)(((Tnodeflag290427) 4))&15U)))!=0); LA9: ; if (!LOC7) goto LA10; result0 = NIM_FALSE; } goto LA5; LA10: ; { Ttype290840* LOC13; LOC13 = (Ttype290840*)0; LOC13 = elemtype_318394_3876443242((*s0).typ); if (!((IL64(62277025792) &((NU64)1<<((NU)((*LOC13).kind)&63U)))!=0)) goto LA14; result0 = NIM_TRUE; } goto LA5; LA14: ; { NI LOC17; LOC17 = (NI)0; LOC17 = sonslen_293351_850551059(s0); result0 = (LOC17 <= ((NI) 8)); } LA5: ; return result0; } N_NIMCALL(void, binaryexprin_553837_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0, NimStringDesc* frmt0) { TY530811 LOC1; Ropeobj177006* LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&(*a0))); LOC1[1] = rdsetelemloc_553662_839829468((&(*b0)), (*a0).t); LOC2 = (Ropeobj177006*)0; LOC2 = HEX25_177905_2381377266(frmt0, LOC1, 2); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0)); } N_NIMCALL(void, geninexpraux_551496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0) { Ttype290840* LOC1; NI64 LOC2; LOC1 = (Ttype290840*)0; LOC1 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC2 = (NI64)0; LOC2 = getsize_318135_3876443242(LOC1); switch (((NI) (LOC2))) { case ((NI) 1): { binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_467)); } break; case ((NI) 2): { binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_468)); } break; case ((NI) 4): { binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_469)); } break; case ((NI) 8): { binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_470)); } break; default: { binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_471)); } break; } } N_NIMCALL(void, geninop_554009_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Tloc290816 x0; Tloc290816 y0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&x0), 0, sizeof(x0)); memset((void*)(&y0), 0, sizeof(y0)); { NIM_BOOL LOC3; Tnode290802* ea0; NI length0; LOC3 = (NIM_BOOL)0; LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind290020) 39)); if (!(LOC3)) goto LA4; LOC3 = fewcmps_553803_839829468((*e0).kindU.S6.sons->data[((NI) 1)]); LA4: ; if (!LOC3) goto LA5; { if (!((*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 70) || (*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 69))) goto LA9; ea0 = (*(*e0).kindU.S6.sons->data[((NI) 2)]).kindU.S6.sons->data[((NI) 0)]; } goto LA7; LA9: ; { ea0 = (*e0).kindU.S6.sons->data[((NI) 2)]; } LA7: ; initlocexpr_537283_839829468(p0, ea0, (&a0)); initloc_530273_839829468((&b0), ((Tlockind290808) 6), (*e0).typ, ((Tstorageloc290812) 0)); b0.r = rope_177277_2381377266(((NimStringDesc*) &T839829468_118)); length0 = sonslen_293351_850551059((*e0).kindU.S6.sons->data[((NI) 1)]); { NI i_554061_839829468; NI HEX3Atmp_554412_839829468; NI res_554415_839829468; i_554061_839829468 = (NI)0; HEX3Atmp_554412_839829468 = (NI)0; HEX3Atmp_554412_839829468 = (NI)(length0 - ((NI) 1)); res_554415_839829468 = ((NI) 0); { while (1) { if (!(res_554415_839829468 <= HEX3Atmp_554412_839829468)) goto LA14; i_554061_839829468 = res_554415_839829468; { TY533238 LOC19; if (!((*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468]).kind == ((Tnodekind290020) 44))) goto LA17; initlocexpr_537283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0)); initlocexpr_537283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0)); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdcharloc_536227_839829468((&a0)); LOC19[1] = rdcharloc_536227_839829468((&x0)); LOC19[2] = rdcharloc_536227_839829468((&y0)); addf_178205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_464), LOC19, 3); } goto LA15; LA17: ; { TY530811 LOC21; initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468], (&x0)); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdcharloc_536227_839829468((&a0)); LOC21[1] = rdcharloc_536227_839829468((&x0)); addf_178205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_465), LOC21, 2); } LA15: ; { if (!(i_554061_839829468 < (NI)(length0 - ((NI) 1)))) goto LA24; add_177487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_466)); } LA24: ; res_554415_839829468 += ((NI) 1); } LA14: ; } } add_177487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_117)); putintodest_548468_839829468(p0, d0, (*e0).typ, b0.r, ((Tstorageloc290812) 0)); } goto LA1; LA5: ; { initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); geninexpraux_551496_839829468(p0, e0, (&a0), (&b0), d0); } LA1: ; } N_NIMCALL(void, gensetop_554419_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) { Tloc290816 a0; Tloc290816 b0; Tloc290816 i0; Ttype290840* settype0; NI size0; NI64 LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&i0), 0, sizeof(i0)); settype0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC1 = (NI64)0; LOC1 = getsize_318135_3876443242(settype0); size0 = ((NI) (LOC1)); switch (size0) { case ((NI) 1): case ((NI) 2): case ((NI) 4): case ((NI) 8): { switch (op0) { case ((Tmagic290524) 39): { NimStringDesc* ts0; NimStringDesc* LOC4; NimStringDesc* LOC5; NimStringDesc* LOC6; LOC4 = (NimStringDesc*)0; LOC5 = (NimStringDesc*)0; LOC5 = nimIntToStr((NI)(size0 * ((NI) 8))); LOC4 = rawNewString(LOC5->Sup.len + 2); appendString(LOC4, ((NimStringDesc*) &T839829468_45)); appendString(LOC4, LOC5); ts0 = LOC4; LOC6 = (NimStringDesc*)0; LOC6 = rawNewString(ts0->Sup.len + ts0->Sup.len + 35); appendString(LOC6, ((NimStringDesc*) &T839829468_449)); appendString(LOC6, ts0); appendString(LOC6, ((NimStringDesc*) &T839829468_450)); appendString(LOC6, ts0); appendString(LOC6, ((NimStringDesc*) &T839829468_451)); binarystmtinexcl_553858_839829468(p0, e0, d0, LOC6); } break; case ((Tmagic290524) 40): { NimStringDesc* ts0; NimStringDesc* LOC8; NimStringDesc* LOC9; NimStringDesc* LOC10; LOC8 = (NimStringDesc*)0; LOC9 = (NimStringDesc*)0; LOC9 = nimIntToStr((NI)(size0 * ((NI) 8))); LOC8 = rawNewString(LOC9->Sup.len + 2); appendString(LOC8, ((NimStringDesc*) &T839829468_45)); appendString(LOC8, LOC9); ts0 = LOC8; LOC10 = (NimStringDesc*)0; LOC10 = rawNewString(ts0->Sup.len + ts0->Sup.len + 42); appendString(LOC10, ((NimStringDesc*) &T839829468_452)); appendString(LOC10, ts0); appendString(LOC10, ((NimStringDesc*) &T839829468_453)); appendString(LOC10, ts0); appendString(LOC10, ((NimStringDesc*) &T839829468_454)); binarystmtinexcl_553858_839829468(p0, e0, d0, LOC10); } break; case ((Tmagic290524) 41): { { if (!(size0 <= ((NI) 4))) goto LA14; unaryexprchar_549222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_455)); } goto LA12; LA14: ; { unaryexprchar_549222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_456)); } LA12: ; } break; case ((Tmagic290524) 133): { binaryexprchar_548809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_457)); } break; case ((Tmagic290524) 132): { binaryexprchar_548809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_458)); } break; case ((Tmagic290524) 131): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341)); } break; case ((Tmagic290524) 134): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_459)); } break; case ((Tmagic290524) 135): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_460)); } break; case ((Tmagic290524) 136): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_461)); } break; case ((Tmagic290524) 137): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_462)); } break; case ((Tmagic290524) 148): { geninop_554009_839829468(p0, e0, d0); } break; default: { internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_472)); } break; } } break; default: { switch (op0) { case ((Tmagic290524) 39): { binarystmtinexcl_553858_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_473)); } break; case ((Tmagic290524) 40): { binarystmtinexcl_553858_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_474)); } break; case ((Tmagic290524) 41): { NimStringDesc* LOC30; NimStringDesc* LOC31; LOC30 = (NimStringDesc*)0; LOC31 = (NimStringDesc*)0; LOC31 = nimIntToStr(size0); LOC30 = rawNewString(LOC31->Sup.len + 14); appendString(LOC30, ((NimStringDesc*) &T839829468_475)); appendString(LOC30, LOC31); appendChar(LOC30, 41); unaryexprchar_549222_839829468(p0, e0, d0, LOC30); } break; case ((Tmagic290524) 133): case ((Tmagic290524) 132): { Ttype290840* LOC33; TY534475 LOC39; LOC33 = (Ttype290840*)0; LOC33 = getsystype_336150_3937434831(((Ttypekind290244) 31)); gettemp_535032_839829468(p0, LOC33, (&i0), NIM_FALSE); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { Ttype290840* LOC38; if (!((*d0).k == ((Tlockind290808) 0))) goto LA36; LOC38 = (Ttype290840*)0; LOC38 = getsystype_336150_3937434831(((Ttypekind290244) 1)); gettemp_535032_839829468(p0, LOC38, d0, NIM_FALSE); } LA36: ; memset((void*)LOC39, 0, sizeof(LOC39)); LOC39[0] = rdloc_536188_839829468((&i0)); LOC39[1] = rope_177401_2381377266(((NI64) (size0))); LOC39[2] = rdloc_536188_839829468((&(*d0))); LOC39[3] = rdloc_536188_839829468((&a0)); LOC39[4] = rdloc_536188_839829468((&b0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), lookupopr_554426_839829468[(op0)- 132], LOC39, 5); } break; case ((Tmagic290524) 131): { NimStringDesc* LOC41; NimStringDesc* LOC42; usestringh_530345_839829468((*p0).module); LOC41 = (NimStringDesc*)0; LOC42 = (NimStringDesc*)0; LOC42 = nimIntToStr(size0); LOC41 = rawNewString(LOC42->Sup.len + 21); appendString(LOC41, ((NimStringDesc*) &T839829468_481)); appendString(LOC41, LOC42); appendString(LOC41, ((NimStringDesc*) &T839829468_482)); binaryexprchar_548809_839829468(p0, e0, d0, LOC41); } break; case ((Tmagic290524) 134): case ((Tmagic290524) 135): case ((Tmagic290524) 136): case ((Tmagic290524) 137): { Ttype290840* LOC44; TY534847 LOC49; LOC44 = (Ttype290840*)0; LOC44 = getsystype_336150_3937434831(((Ttypekind290244) 31)); gettemp_535032_839829468(p0, LOC44, (&i0), NIM_FALSE); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA47; gettemp_535032_839829468(p0, a0.t, d0, NIM_FALSE); } LA47: ; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_536188_839829468((&i0)); LOC49[1] = rope_177401_2381377266(((NI64) (size0))); LOC49[2] = rdloc_536188_839829468((&(*d0))); LOC49[3] = rdloc_536188_839829468((&a0)); LOC49[4] = rdloc_536188_839829468((&b0)); LOC49[5] = rope_177277_2381377266(lookupopr_554426_839829468[(op0)- 132]); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_483), LOC49, 6); } break; case ((Tmagic290524) 148): { geninop_554009_839829468(p0, e0, d0); } break; default: { internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_484)); } break; } } break; } } static N_INLINE(Ropeobj177006*, genargstringtocstring_537776_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; Tloc290816 a0; TY177507 LOC1; result0 = (Ropeobj177006*)0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_485), LOC1, 1); return result0; } N_NIMCALL(Ropeobj177006*, openarrayloc_537665_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; Tloc290816 a0; Tnode290802* q0; result0 = (Ropeobj177006*)0; memset((void*)(&a0), 0, sizeof(a0)); q0 = skipconv_326882_3876443242(n0); { Tmagic290524 LOC3; Tloc290816 b0; Tloc290816 c0; Tnode290802* LOC6; Tnode290802* LOC7; Tnode290802* LOC8; NimStringDesc* fmt0; Ttype290840* LOC9; TY533238 LOC25; LOC3 = (Tmagic290524)0; LOC3 = getmagic_316502_2616423590(q0); if (!(LOC3 == ((Tmagic290524) 139))) goto LA4; memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&c0), 0, sizeof(c0)); LOC6 = (Tnode290802*)0; LOC6 = HEX5BHEX5D_291238_850551059(q0, ((NI) 1)); initlocexpr_537283_839829468(p0, LOC6, (&a0)); LOC7 = (Tnode290802*)0; LOC7 = HEX5BHEX5D_291238_850551059(q0, ((NI) 2)); initlocexpr_537283_839829468(p0, LOC7, (&b0)); LOC8 = (Tnode290802*)0; LOC8 = HEX5BHEX5D_291238_850551059(q0, ((NI) 3)); initlocexpr_537283_839829468(p0, LOC8, (&c0)); LOC9 = (Ttype290840*)0; LOC9 = skiptypes_294099_850551059(a0.t, IL64(211106243062016)); switch ((*LOC9).kind) { case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { fmt0 = copyString(((NimStringDesc*) &T839829468_486)); } break; case ((Ttypekind290244) 28): case ((Ttypekind290244) 24): { { NIM_BOOL LOC14; Ttype290840* LOC15; NIM_BOOL LOC17; LOC14 = (NIM_BOOL)0; LOC15 = (Ttype290840*)0; LOC15 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256)); LOC14 = ((*LOC15).kind == ((Ttypekind290244) 23)); if (!(LOC14)) goto LA16; LOC17 = (NIM_BOOL)0; LOC17 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC17) goto LA18; LOC17 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA18: ; LOC14 = !(LOC17); LA16: ; if (!LOC14) goto LA19; fmt0 = copyString(((NimStringDesc*) &T839829468_487)); } goto LA12; LA19: ; { fmt0 = copyString(((NimStringDesc*) &T839829468_488)); } LA12: ; } break; default: { NimStringDesc* LOC23; NimStringDesc* LOC24; LOC23 = (NimStringDesc*)0; LOC24 = (NimStringDesc*)0; LOC24 = typetostring_318017_3876443242(a0.t, ((Tprefereddesc318011) 0)); LOC23 = rawNewString(LOC24->Sup.len + 14); appendString(LOC23, ((NimStringDesc*) &T839829468_489)); appendString(LOC23, LOC24); internalerror_194113_155036129(LOC23); fmt0 = copyString(((NimStringDesc*) &T839829468_490)); } break; } memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = rdloc_536188_839829468((&a0)); LOC25[1] = rdloc_536188_839829468((&b0)); LOC25[2] = rdloc_536188_839829468((&c0)); result0 = HEX25_177905_2381377266(fmt0, LOC25, 3); } goto LA1; LA4: ; { Ttype290840* LOC27; initlocexpr_537283_839829468(p0, n0, (&a0)); LOC27 = (Ttype290840*)0; LOC27 = skiptypes_294099_850551059(a0.t, IL64(211106240964864)); switch ((*LOC27).kind) { case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { TY177507 LOC29; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdloc_536188_839829468((&a0)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_378), LOC29, 1); } break; case ((Ttypekind290244) 28): case ((Ttypekind290244) 24): { { NIM_BOOL LOC33; Ttype290840* LOC34; NIM_BOOL LOC36; TY530811 LOC40; LOC33 = (NIM_BOOL)0; LOC34 = (Ttype290840*)0; LOC34 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256)); LOC33 = ((*LOC34).kind == ((Ttypekind290244) 23)); if (!(LOC33)) goto LA35; LOC36 = (NIM_BOOL)0; LOC36 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC36) goto LA37; LOC36 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA37: ; LOC33 = !(LOC36); LA35: ; if (!LOC33) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = rdloc_536188_839829468((&a0)); LOC40[1] = lenfield_537305_839829468(p0); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_491), LOC40, 2); } goto LA31; LA38: ; { TY530811 LOC42; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = rdloc_536188_839829468((&a0)); LOC42[1] = lenfield_537305_839829468(p0); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_379), LOC42, 2); } LA31: ; } break; case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { TY530811 LOC44; NI64 LOC45; memset((void*)LOC44, 0, sizeof(LOC44)); LOC44[0] = rdloc_536188_839829468((&a0)); LOC45 = (NI64)0; LOC45 = lengthord_318007_3876443242(a0.t); LOC44[1] = rope_177401_2381377266(LOC45); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_380), LOC44, 2); } break; case ((Ttypekind290244) 21): case ((Ttypekind290244) 22): { Ttype290840* LOC47; LOC47 = (Ttype290840*)0; LOC47 = lastson_293377_850551059(a0.t); switch ((*LOC47).kind) { case ((Ttypekind290244) 28): case ((Ttypekind290244) 24): { TY530811 LOC49; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_536188_839829468((&a0)); LOC49[1] = lenfield_537305_839829468(p0); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_491), LOC49, 2); } break; case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { TY530811 LOC51; Ttype290840* LOC52; NI64 LOC53; memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = rdloc_536188_839829468((&a0)); LOC52 = (Ttype290840*)0; LOC52 = lastson_293377_850551059(a0.t); LOC53 = (NI64)0; LOC53 = lengthord_318007_3876443242(LOC52); LOC51[1] = rope_177401_2381377266(LOC53); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_380), LOC51, 2); } break; default: { NimStringDesc* LOC55; NimStringDesc* LOC56; LOC55 = (NimStringDesc*)0; LOC56 = (NimStringDesc*)0; LOC56 = typetostring_318017_3876443242(a0.t, ((Tprefereddesc318011) 0)); LOC55 = rawNewString(LOC56->Sup.len + 14); appendString(LOC55, ((NimStringDesc*) &T839829468_489)); appendString(LOC55, LOC56); internalerror_194113_155036129(LOC55); } break; } } break; default: { NimStringDesc* LOC58; NimStringDesc* LOC59; LOC58 = (NimStringDesc*)0; LOC59 = (NimStringDesc*)0; LOC59 = typetostring_318017_3876443242(a0.t, ((Tprefereddesc318011) 0)); LOC58 = rawNewString(LOC59->Sup.len + 14); appendString(LOC58, ((NimStringDesc*) &T839829468_489)); appendString(LOC58, LOC59); internalerror_194113_155036129(LOC58); } break; } } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, genarg_537787_839829468)(Tcproc527021* p0, Tnode290802* n_537790_839829468, Tsym290834* param0, Tnode290802* call0) { Ropeobj177006* result0; Tloc290816 a0; result0 = (Ropeobj177006*)0; memset((void*)(&a0), 0, sizeof(a0)); { if (!((*n_537790_839829468).kind == ((Tnodekind290020) 71))) goto LA3; result0 = genargstringtocstring_537776_839829468(p0, n_537790_839829468); } goto LA1; LA3: ; { Ttype290840* LOC6; Tnode290802* n0; LOC6 = (Ttype290840*)0; LOC6 = skiptypes_294099_850551059((*param0).typ, IL64(211106240964864)); if (!((IL64(281475110928384) &((NU64)1<<((NU)((*LOC6).kind)&63U)))!=0)) goto LA7; { if (!!(((*n_537790_839829468).kind == ((Tnodekind290020) 64)))) goto LA11; n0 = n_537790_839829468; } goto LA9; LA11: ; { n0 = (*n_537790_839829468).kindU.S6.sons->data[((NI) 0)]; } LA9: ; result0 = openarrayloc_537665_839829468(p0, n0); } goto LA1; LA7: ; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = ccgintroducedptr_531611_839829468(param0); if (!LOC15) goto LA16; initlocexpr_537283_839829468(p0, n_537790_839829468, (&a0)); result0 = addrloc_536204_839829468((&a0)); } goto LA1; LA16: ; { NIM_BOOL LOC19; NIM_BOOL LOC20; NIM_BOOL LOC21; Tnode290802* callee0; LOC19 = (NIM_BOOL)0; LOC20 = (NIM_BOOL)0; LOC21 = (NIM_BOOL)0; LOC21 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC21) goto LA22; LOC21 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA22: ; LOC20 = LOC21; if (!(LOC20)) goto LA23; LOC20 = ((*(*param0).typ).kind == ((Ttypekind290244) 23)); LA23: ; LOC19 = LOC20; if (!(LOC19)) goto LA24; LOC19 = ((*n_537790_839829468).kind == ((Tnodekind290020) 64)); LA24: ; if (!LOC19) goto LA25; initlocexprsingleuse_537289_839829468(p0, (*n_537790_839829468).kindU.S6.sons->data[((NI) 0)], (&a0)); callee0 = (*call0).kindU.S6.sons->data[((NI) 0)]; { NIM_BOOL LOC29; NIM_BOOL LOC30; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((*callee0).kind == ((Tnodekind290020) 3)); if (!(LOC30)) goto LA31; LOC30 = ((134283296 & (*(*callee0).kindU.S4.sym).flags) == 32); LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA32; LOC29 = !(((72 & (*(*callee0).kindU.S4.sym).loc.flags) == 0)); LA32: ; if (!LOC29) goto LA33; result0 = addrloc_536204_839829468((&a0)); } goto LA27; LA33: ; { result0 = rdloc_536188_839829468((&a0)); } LA27: ; } goto LA1; LA25: ; { initlocexprsingleuse_537289_839829468(p0, n_537790_839829468, (&a0)); result0 = rdloc_536188_839829468((&a0)); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, genargnoparam_537938_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; Tloc290816 a0; result0 = (Ropeobj177006*)0; memset((void*)(&a0), 0, sizeof(a0)); { if (!((*n0).kind == ((Tnodekind290020) 71))) goto LA3; result0 = genargstringtocstring_537776_839829468(p0, n0); } goto LA1; LA3: ; { initlocexprsingleuse_537289_839829468(p0, n0, (&a0)); result0 = rdloc_536188_839829468((&a0)); } LA1: ; return result0; } N_NIMCALL(Ropeobj177006*, getrawproctype_538459_839829468)(Tcproc527021* p0, Ttype290840* t0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = getclosuretype_533685_839829468((*p0).module, t0, ((Tclosuretypekind533681) 0)); return result0; } N_NIMCALL(NIM_BOOL, leftappearsonrightside_537329_839829468)(Tnode290802* le0, Tnode290802* ri0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!!((le0 == NIM_NIL))) goto LA3; { NI i_537364_839829468; NI HEX3Atmp_537376_839829468; NI LOC6; NI res_537379_839829468; i_537364_839829468 = (NI)0; HEX3Atmp_537376_839829468 = (NI)0; LOC6 = (NI)0; LOC6 = len_291081_850551059(ri0); HEX3Atmp_537376_839829468 = (LOC6 - 1); res_537379_839829468 = ((NI) 1); { while (1) { Tnode290802* r0; if (!(res_537379_839829468 <= HEX3Atmp_537376_839829468)) goto LA8; i_537364_839829468 = res_537379_839829468; r0 = HEX5BHEX5D_291238_850551059(ri0, i_537364_839829468); { Tanalysisresult471003 LOC11; LOC11 = (Tanalysisresult471003)0; LOC11 = ispartof_471340_788060399(le0, r0); if (!!((LOC11 == ((Tanalysisresult471003) 0)))) goto LA12; result0 = NIM_TRUE; goto BeforeRet; } LA12: ; res_537379_839829468 += ((NI) 1); } LA8: ; } } } LA3: ; }BeforeRet: ; return result0; } static N_INLINE(NIM_BOOL, hasnoinit_537383_839829468)(Tnode290802* call0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((*(*call0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC1)) goto LA2; LOC1 = (((*(*(*call0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, resetloc_536350_839829468)(Tcproc527021* p0, Tloc290816* loc0) { NIM_BOOL containsgcref0; Ttype290840* typ0; { containsgcref0 = containsgarbagecollectedref_318117_3876443242((*loc0).t); typ0 = skiptypes_294099_850551059((*loc0).t, IL64(211106242013440)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedcpptype_531478_839829468(typ0); if (!LOC3) goto LA4; goto BeforeRet; } LA4: ; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = iscomplexvaluetype_536317_839829468(typ0); if (!!(LOC8)) goto LA9; { Tloc290816 nilloc0; if (!containsgcref0) goto LA13; memset((void*)(&nilloc0), 0, sizeof(nilloc0)); initloc_530273_839829468((&nilloc0), ((Tlockind290808) 1), (*loc0).t, ((Tstorageloc290812) 2)); nilloc0.r = rope_177277_2381377266(((NimStringDesc*) &T839829468_174)); genrefassign_536311_839829468(p0, (&(*loc0)), (&nilloc0), 8); } goto LA11; LA13: ; { TY177507 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_536188_839829468((&(*loc0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_494), LOC16, 1); } LA11: ; } goto LA6; LA9: ; { { TY177507 LOC22; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 6))&31U)))!=0)) goto LA20; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = addrloc_536204_839829468((&(*loc0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_495), LOC22, 1); } LA20: ; { TY530811 LOC27; if (!!(((*loc0).s == ((Tstorageloc290812) 2)))) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = addrloc_536204_839829468((&(*loc0))); LOC27[1] = gentypeinfo_533941_839829468((*p0).module, (*loc0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_496), LOC27, 2); genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), (*loc0).t, (&(*loc0)), NIM_TRUE); } goto LA23; LA25: ; { TY530811 LOC29; usestringh_530345_839829468((*p0).module); memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = addrloc_536204_839829468((&(*loc0))); LOC29[1] = rdloc_536188_839829468((&(*loc0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_152), LOC29, 2); genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), (*loc0).t, (&(*loc0)), NIM_TRUE); } LA23: ; } LA6: ; }BeforeRet: ; } N_NIMCALL(Ropeobj177006*, addcomma_538464_839829468)(Ropeobj177006* r0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { if (!(r0 == NIM_NIL)) goto LA3; result0 = r0; } goto LA1; LA3: ; { TY531289 LOC6; Ropeobj177006* LOC7; memset((void*)LOC6, 0, sizeof(LOC6)); LOC7 = (Ropeobj177006*)0; LOC7 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC6, 0); result0 = HEX26_177418_2381377266(r0, LOC7); } LA1: ; return result0; } N_NIMCALL(void, genclosurecall_538452_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) { Tloc290816 op0; Ropeobj177006* pl0; Ttype290840* typ0; NI length0; Ropeobj177006* rawproc0; NimStringDesc* callpattern0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); pl0 = (Ropeobj177006*)0; typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_293351_850551059(ri0); { NI i_538613_839829468; NI HEX3Atmp_539214_839829468; NI res_539217_839829468; i_538613_839829468 = (NI)0; HEX3Atmp_539214_839829468 = (NI)0; HEX3Atmp_539214_839829468 = (NI)(length0 - ((NI) 1)); res_539217_839829468 = ((NI) 1); { while (1) { if (!(res_539217_839829468 <= HEX3Atmp_539214_839829468)) goto LA3; i_538613_839829468 = res_539217_839829468; { NI LOC6; Tnode290802* paramtype0; LOC6 = (NI)0; LOC6 = sonslen_293327_850551059(typ0); if (!(i_538613_839829468 < LOC6)) goto LA7; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_538613_839829468]; { NIM_BOOL LOC11; Ropeobj177006* LOC20; LOC11 = (NIM_BOOL)0; LOC11 = iscompiletimeonly_326706_3876443242((*paramtype0).typ); if (!!(LOC11)) goto LA12; { TY531289 LOC18; Ropeobj177006* LOC19; if (!!((pl0 == NIM_NIL))) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (Ropeobj177006*)0; LOC19 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0); add_177482_2381377266(&pl0, LOC19); } LA16: ; LOC20 = (Ropeobj177006*)0; LOC20 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[i_538613_839829468], (*paramtype0).kindU.S4.sym, ri0); add_177482_2381377266(&pl0, LOC20); } LA12: ; } goto LA4; LA7: ; { Ropeobj177006* LOC28; { TY531289 LOC26; Ropeobj177006* LOC27; if (!!((pl0 == NIM_NIL))) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC27 = (Ropeobj177006*)0; LOC27 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0); add_177482_2381377266(&pl0, LOC27); } LA24: ; LOC28 = (Ropeobj177006*)0; LOC28 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i_538613_839829468]); add_177482_2381377266(&pl0, LOC28); } LA4: ; res_539217_839829468 += ((NI) 1); } LA3: ; } } rawproc0 = getrawproctype_538459_839829468(p0, typ0); { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 14))&31U)))!=0)) goto LA31; callpattern0 = copyString(((NimStringDesc*) &T839829468_492)); } goto LA29; LA31: ; { callpattern0 = copyString(((NimStringDesc*) &T839829468_493)); } LA29: ; { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA36; { NIM_BOOL LOC40; LOC40 = (NIM_BOOL)0; LOC40 = isinvalidreturntype_531550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC40) goto LA41; { NI LOC45; TY531289 LOC48; Ropeobj177006* LOC49; LOC45 = (NI)0; LOC45 = sonslen_293351_850551059(ri0); if (!(((NI) 1) < LOC45)) goto LA46; memset((void*)LOC48, 0, sizeof(LOC48)); LOC49 = (Ropeobj177006*)0; LOC49 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC48, 0); add_177482_2381377266(&pl0, LOC49); } LA46: ; { NIM_BOOL LOC52; NIM_BOOL LOC54; Ropeobj177006* LOC67; NimStringDesc* LOC68; TY533235 LOC69; LOC52 = (NIM_BOOL)0; LOC52 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0); if (LOC52) goto LA53; LOC54 = (NIM_BOOL)0; LOC54 = leftappearsonrightside_537329_839829468(le0, ri0); LOC52 = !(LOC54); LA53: ; if (!LOC52) goto LA55; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA59; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } goto LA57; LA59: ; { NIM_BOOL LOC62; NIM_BOOL LOC64; LOC62 = (NIM_BOOL)0; LOC62 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0)); if (!(LOC62)) goto LA63; LOC64 = (NIM_BOOL)0; LOC64 = hasnoinit_537383_839829468(ri0); LOC62 = !(LOC64); LA63: ; if (!LOC62) goto LA65; resetloc_536350_839829468(p0, d0); } goto LA57; LA65: ; LA57: ; LOC67 = (Ropeobj177006*)0; LOC67 = addrloc_536204_839829468((&(*d0))); add_177482_2381377266(&pl0, LOC67); LOC68 = (NimStringDesc*)0; LOC68 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC68, callpattern0); appendString(LOC68, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC69, 0, sizeof(LOC69)); LOC69[0] = op0.r; LOC69[1] = pl0; LOC69[2] = addcomma_538464_839829468(pl0); LOC69[3] = rawproc0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC68, LOC69, 4); } goto LA50; LA55: ; { Tloc290816 tmp0; Ropeobj177006* LOC71; NimStringDesc* LOC72; TY533235 LOC73; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC71 = (Ropeobj177006*)0; LOC71 = addrloc_536204_839829468((&tmp0)); add_177482_2381377266(&pl0, LOC71); LOC72 = (NimStringDesc*)0; LOC72 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC72, callpattern0); appendString(LOC72, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = op0.r; LOC73[1] = pl0; LOC73[2] = addcomma_538464_839829468(pl0); LOC73[3] = rawproc0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC72, LOC73, 4); genassignment_537264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA50: ; } goto LA38; LA41: ; { Tloc290816 list0; TY533235 LOC79; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA77; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA77: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_530273_839829468((&list0), ((Tlockind290808) 9), (*d0).t, ((Tstorageloc290812) 0)); memset((void*)LOC79, 0, sizeof(LOC79)); LOC79[0] = op0.r; LOC79[1] = pl0; LOC79[2] = addcomma_538464_839829468(pl0); LOC79[3] = rawproc0; list0.r = HEX25_177905_2381377266(callpattern0, LOC79, 4); genassignment_537264_839829468(p0, (&(*d0)), (&list0), 0); } LA38: ; } goto LA34; LA36: ; { NimStringDesc* LOC81; TY533235 LOC82; LOC81 = (NimStringDesc*)0; LOC81 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC81, callpattern0); appendString(LOC81, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC82, 0, sizeof(LOC82)); LOC82[0] = op0.r; LOC82[1] = pl0; LOC82[2] = addcomma_538464_839829468(pl0); LOC82[3] = rawproc0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC81, LOC82, 4); } LA34: ; } N_NIMCALL(Ropeobj177006*, genotherarg_537277_839829468)(Tcproc527021* p0, Tnode290802* ri0, NI i0, Ttype290840* typ0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NI LOC3; Tnode290802* paramtype0; LOC3 = (NI)0; LOC3 = sonslen_293327_850551059(typ0); if (!(i0 < LOC3)) goto LA4; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i0]; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = iscompiletimeonly_326706_3876443242((*paramtype0).typ); if (!LOC8) goto LA9; result0 = NIM_NIL; } goto LA6; LA9: ; { NIM_BOOL LOC12; Tnode290802* LOC16; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*typ0).sons->data[i0]).kind == ((Ttypekind290244) 23)); if (!(LOC12)) goto LA13; LOC12 = ((*(*ri0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 64)); LA13: ; if (!LOC12) goto LA14; LOC16 = (Tnode290802*)0; LOC16 = HEX5BHEX5D_291238_850551059((*ri0).kindU.S6.sons->data[i0], ((NI) 0)); result0 = genargnoparam_537938_839829468(p0, LOC16); } goto LA6; LA14: ; { result0 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]); } LA6: ; } goto LA1; LA4: ; { { if (!!((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0))) goto LA21; localerror_194085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_501)); result0 = NIM_NIL; } goto LA19; LA21: ; { result0 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]); } LA19: ; } LA1: ; return result0; } N_NIMCALL(Tnode290802*, skipaddrderef_539433_839829468)(Tnode290802* node0) { Tnode290802* result0; Tnode290802* n0; NIM_BOOL isaddr0; { result0 = (Tnode290802*)0; n0 = node0; isaddr0 = NIM_FALSE; switch ((*n0).kind) { case ((Tnodekind290020) 63): case ((Tnodekind290020) 64): { n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; isaddr0 = NIM_TRUE; } break; case ((Tnodekind290020) 47): case ((Tnodekind290020) 65): { n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } break; default: { result0 = n0; goto BeforeRet; } break; } { if (!((*n0).kind == ((Tnodekind290020) 66))) goto LA6; n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } LA6: ; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = isaddr0; if (!(LOC10)) goto LA11; LOC10 = ((*n0).kind == ((Tnodekind290020) 47) || (*n0).kind == ((Tnodekind290020) 65)); LA11: ; if (!LOC10) goto LA12; result0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } goto LA8; LA12: ; { if (!((*n0).kind == ((Tnodekind290020) 63) || (*n0).kind == ((Tnodekind290020) 64))) goto LA15; result0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } goto LA8; LA15: ; { result0 = node0; } LA8: ; }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj177006*, genthisarg_539475_839829468)(Tcproc527021* p0, Tnode290802* ri_539478_839829468, NI i0, Ttype290840* typ0) { Ropeobj177006* result0; Tnode290802* ri0; Ttype290840* t0; result0 = (Ropeobj177006*)0; { NI LOC3; NimStringDesc* LOC6; LOC3 = (NI)0; LOC3 = sonslen_293327_850551059(typ0); if (!!((i0 < LOC3))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_194185_1689653243(T839829468_503); internalerror_194113_155036129(LOC6); } LA4: ; ri0 = HEX5BHEX5D_291238_850551059(ri_539478_839829468, i0); { while (1) { if (!((*ri0).kind == ((Tnodekind290020) 66))) goto LA8; ri0 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0)); } LA8: ; } t0 = skiptypes_294099_850551059((*typ0).sons->data[i0], 2048); { Tnode290802* x0; if (!((*t0).kind == ((Ttypekind290244) 23))) goto LA11; { if (!((*ri0).kind == ((Tnodekind290020) 64))) goto LA15; x0 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0)); } goto LA13; LA15: ; { x0 = ri0; } LA13: ; { if (!((*(*x0).typ).kind == ((Ttypekind290244) 21))) goto LA20; result0 = genargnoparam_537938_839829468(p0, x0); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } goto LA18; LA20: ; { NIM_BOOL LOC23; Tnode290802* LOC25; Tnode290802* LOC28; LOC23 = (NIM_BOOL)0; LOC23 = ((*x0).kind == ((Tnodekind290020) 65) || (*x0).kind == ((Tnodekind290020) 47)); if (!(LOC23)) goto LA24; LOC25 = (Tnode290802*)0; LOC25 = HEX5BHEX5D_291238_850551059(x0, ((NI) 0)); LOC23 = ((*(*LOC25).typ).kind == ((Ttypekind290244) 21)); LA24: ; if (!LOC23) goto LA26; LOC28 = (Tnode290802*)0; LOC28 = HEX5BHEX5D_291238_850551059(x0, ((NI) 0)); result0 = genargnoparam_537938_839829468(p0, LOC28); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } goto LA18; LA26: ; { result0 = genargnoparam_537938_839829468(p0, x0); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } LA18: ; } goto LA9; LA11: ; { if (!((*t0).kind == ((Ttypekind290244) 21))) goto LA31; { Tnode290802* LOC37; if (!((*ri0).kind == ((Tnodekind290020) 63) || (*ri0).kind == ((Tnodekind290020) 64))) goto LA35; LOC37 = (Tnode290802*)0; LOC37 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0)); result0 = genargnoparam_537938_839829468(p0, LOC37); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } goto LA33; LA35: ; { result0 = genargnoparam_537938_839829468(p0, ri0); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } LA33: ; } goto LA9; LA31: ; { ri0 = skipaddrderef_539433_839829468(ri0); { if (!((*ri0).kind == ((Tnodekind290020) 63) || (*ri0).kind == ((Tnodekind290020) 64))) goto LA42; ri0 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0)); } LA42: ; result0 = genargnoparam_537938_839829468(p0, ri0); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } LA9: ; return result0; } N_NIMCALL(Ropeobj177006*, genpatterncall_539699_839829468)(Tcproc527021* p0, Tnode290802* ri_539702_839829468, NimStringDesc* pat0, Ttype290840* typ_539704_839829468) { Ropeobj177006* result0; NI i0; NI j0; result0 = (Ropeobj177006*)0; i0 = ((NI) 0); j0 = ((NI) 1); { while (1) { if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA2; switch (((NU8)(pat0->data[i0]))) { case 64: { { NI LOC6; Ropeobj177006* LOC9; LOC6 = (NI)0; LOC6 = len_291081_850551059(ri_539702_839829468); if (!(j0 < LOC6)) goto LA7; LOC9 = (Ropeobj177006*)0; LOC9 = genotherarg_537277_839829468(p0, ri_539702_839829468, j0, typ_539704_839829468); add_177482_2381377266(&result0, LOC9); { NI k_539728_839829468; NI HEX3Atmp_539904_839829468; NI HEX3Atmp_539905_839829468; NI LOC11; NI res_539908_839829468; k_539728_839829468 = (NI)0; HEX3Atmp_539904_839829468 = (NI)0; HEX3Atmp_539905_839829468 = (NI)0; HEX3Atmp_539904_839829468 = (NI)(j0 + ((NI) 1)); LOC11 = (NI)0; LOC11 = len_291081_850551059(ri_539702_839829468); HEX3Atmp_539905_839829468 = (LOC11 - 1); res_539908_839829468 = HEX3Atmp_539904_839829468; { while (1) { TY531289 LOC14; Ropeobj177006* LOC15; Ropeobj177006* LOC16; if (!(res_539908_839829468 <= HEX3Atmp_539905_839829468)) goto LA13; k_539728_839829468 = res_539908_839829468; memset((void*)LOC14, 0, sizeof(LOC14)); LOC15 = (Ropeobj177006*)0; LOC15 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC14, 0); add_177482_2381377266(&result0, LOC15); LOC16 = (Ropeobj177006*)0; LOC16 = genotherarg_537277_839829468(p0, ri_539702_839829468, k_539728_839829468, typ_539704_839829468); add_177482_2381377266(&result0, LOC16); res_539908_839829468 += ((NI) 1); } LA13: ; } } } LA7: ; i0 += ((NI) 1); } break; case 35: { { Tnode290802* ri0; if (!(((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(43)) || ((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(64)))) goto LA20; ri0 = HEX5BHEX5D_291238_850551059(ri_539702_839829468, j0); { Ttype290840* typ0; TY531289 LOC31; Ropeobj177006* LOC32; TY531289 LOC46; Ropeobj177006* LOC47; if (!((*ri0).kind == ((Tnodekind290020) 27) || (*ri0).kind == ((Tnodekind290020) 29) || (*ri0).kind == ((Tnodekind290020) 30) || (*ri0).kind == ((Tnodekind290020) 31) || (*ri0).kind == ((Tnodekind290020) 26) || (*ri0).kind == ((Tnodekind290020) 28) || (*ri0).kind == ((Tnodekind290020) 32))) goto LA24; typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { Ropeobj177006* LOC30; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(43))) goto LA28; LOC30 = (Ropeobj177006*)0; LOC30 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)]); add_177482_2381377266(&result0, LOC30); } LA28: ; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj177006*)0; LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_118), LOC31, 0); add_177482_2381377266(&result0, LOC32); { NI LOC35; Ropeobj177006* LOC38; LOC35 = (NI)0; LOC35 = len_291081_850551059(ri0); if (!(((NI) 1) < LOC35)) goto LA36; LOC38 = (Ropeobj177006*)0; LOC38 = genotherarg_537277_839829468(p0, ri0, ((NI) 1), typ0); add_177482_2381377266(&result0, LOC38); } LA36: ; { NI k_539793_839829468; NI HEX3Atmp_539915_839829468; NI HEX3Atmp_539916_839829468; NI LOC40; NI res_539919_839829468; k_539793_839829468 = (NI)0; HEX3Atmp_539915_839829468 = (NI)0; HEX3Atmp_539916_839829468 = (NI)0; HEX3Atmp_539915_839829468 = (NI)(j0 + ((NI) 1)); LOC40 = (NI)0; LOC40 = len_291081_850551059(ri0); HEX3Atmp_539916_839829468 = (LOC40 - 1); res_539919_839829468 = HEX3Atmp_539915_839829468; { while (1) { TY531289 LOC43; Ropeobj177006* LOC44; Ropeobj177006* LOC45; if (!(res_539919_839829468 <= HEX3Atmp_539916_839829468)) goto LA42; k_539793_839829468 = res_539919_839829468; memset((void*)LOC43, 0, sizeof(LOC43)); LOC44 = (Ropeobj177006*)0; LOC44 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC43, 0); add_177482_2381377266(&result0, LOC44); LOC45 = (Ropeobj177006*)0; LOC45 = genotherarg_537277_839829468(p0, ri0, k_539793_839829468, typ0); add_177482_2381377266(&result0, LOC45); res_539919_839829468 += ((NI) 1); } LA42: ; } } memset((void*)LOC46, 0, sizeof(LOC46)); LOC47 = (Ropeobj177006*)0; LOC47 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_117), LOC46, 0); add_177482_2381377266(&result0, LOC47); } goto LA22; LA24: ; { localerror_194085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_502)); } LA22: ; i0 += ((NI) 1); } goto LA18; LA20: ; { Ropeobj177006* LOC52; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(46))) goto LA50; LOC52 = (Ropeobj177006*)0; LOC52 = genthisarg_539475_839829468(p0, ri_539702_839829468, j0, typ_539704_839829468); add_177482_2381377266(&result0, LOC52); i0 += ((NI) 1); } goto LA18; LA50: ; { Tnode290802* arg0; Ropeobj177006* LOC58; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(91))) goto LA54; arg0 = skipaddrderef_539433_839829468((*ri_539702_839829468).kindU.S6.sons->data[j0]); { while (1) { if (!((*arg0).kind == ((Tnodekind290020) 63) || (*arg0).kind == ((Tnodekind290020) 64) || (*arg0).kind == ((Tnodekind290020) 66))) goto LA57; arg0 = HEX5BHEX5D_291238_850551059(arg0, ((NI) 0)); } LA57: ; } LOC58 = (Ropeobj177006*)0; LOC58 = genargnoparam_537938_839829468(p0, arg0); add_177482_2381377266(&result0, LOC58); } goto LA18; LA54: ; { Ropeobj177006* LOC60; LOC60 = (Ropeobj177006*)0; LOC60 = genotherarg_537277_839829468(p0, ri_539702_839829468, j0, typ_539704_839829468); add_177482_2381377266(&result0, LOC60); } LA18: ; j0 += ((NI) 1); i0 += ((NI) 1); } break; case 39: { NI idx0; NI stars0; idx0 = (NI)0; stars0 = (NI)0; { NIM_BOOL LOC64; Ttype290840* t0; LOC64 = (NIM_BOOL)0; LOC64 = scancppgenericslot_532827_839829468(pat0, (&i0), (&idx0), (&stars0)); if (!LOC64) goto LA65; t0 = resolvestarsincpptype_532891_839829468(typ_539704_839829468, idx0, stars0); { TY531289 LOC71; Ropeobj177006* LOC72; if (!(t0 == NIM_NIL)) goto LA69; memset((void*)LOC71, 0, sizeof(LOC71)); LOC72 = (Ropeobj177006*)0; LOC72 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_26), LOC71, 0); add_177482_2381377266(&result0, LOC72); } goto LA67; LA69: ; { Ropeobj177006* LOC74; LOC74 = (Ropeobj177006*)0; LOC74 = gettypedesc_533673_839829468((*p0).module, t0); add_177482_2381377266(&result0, LOC74); } LA67: ; } LA65: ; } break; default: { NI start0; start0 = i0; { while (1) { if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA77; { if (!!((((NU8)(pat0->data[i0])) == ((NU8)(64)) || ((NU8)(pat0->data[i0])) == ((NU8)(35)) || ((NU8)(pat0->data[i0])) == ((NU8)(39))))) goto LA80; i0 += ((NI) 1); } goto LA78; LA80: ; { goto LA76; } LA78: ; } LA77: ; } LA76: ; { NimStringDesc* LOC87; if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA85; LOC87 = (NimStringDesc*)0; LOC87 = copyStrLast(pat0, start0, (NI)(i0 - ((NI) 1))); add_177487_2381377266(&result0, LOC87); } LA85: ; } break; } } LA2: ; } return result0; } N_NIMCALL(void, fixupcall_537410_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0, Ropeobj177006* callee0, Ropeobj177006* params0) { Ropeobj177006* pl0; TY531289 LOC1; Ropeobj177006* LOC2; Ropeobj177006* LOC3; Ttype290840* typ0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (Ropeobj177006*)0; LOC2 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_118), LOC1, 0); LOC3 = (Ropeobj177006*)0; LOC3 = HEX26_177418_2381377266(callee0, LOC2); pl0 = HEX26_177418_2381377266(LOC3, params0); typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA6; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = isinvalidreturntype_531550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC10) goto LA11; { TY531289 LOC17; Ropeobj177006* LOC18; if (!!((params0 == NIM_NIL))) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC18 = (Ropeobj177006*)0; LOC18 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC17, 0); add_177482_2381377266(&pl0, LOC18); } LA15: ; { NIM_BOOL LOC21; NIM_BOOL LOC23; Ropeobj177006* LOC36; TY531289 LOC37; Ropeobj177006* LOC38; LOC21 = (NIM_BOOL)0; LOC21 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0); if (LOC21) goto LA22; LOC23 = (NIM_BOOL)0; LOC23 = leftappearsonrightside_537329_839829468(le0, ri0); LOC21 = !(LOC23); LA22: ; if (!LOC21) goto LA24; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA28; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } goto LA26; LA28: ; { NIM_BOOL LOC31; NIM_BOOL LOC33; LOC31 = (NIM_BOOL)0; LOC31 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0)); if (!(LOC31)) goto LA32; LOC33 = (NIM_BOOL)0; LOC33 = hasnoinit_537383_839829468(ri0); LOC31 = !(LOC33); LA32: ; if (!LOC31) goto LA34; resetloc_536350_839829468(p0, d0); } goto LA26; LA34: ; LA26: ; LOC36 = (Ropeobj177006*)0; LOC36 = addrloc_536204_839829468((&(*d0))); add_177482_2381377266(&pl0, LOC36); memset((void*)LOC37, 0, sizeof(LOC37)); LOC38 = (Ropeobj177006*)0; LOC38 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_505), LOC37, 0); add_177482_2381377266(&pl0, LOC38); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); } goto LA19; LA24: ; { Tloc290816 tmp0; Ropeobj177006* LOC40; TY531289 LOC41; Ropeobj177006* LOC42; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC40 = (Ropeobj177006*)0; LOC40 = addrloc_536204_839829468((&tmp0)); add_177482_2381377266(&pl0, LOC40); memset((void*)LOC41, 0, sizeof(LOC41)); LOC42 = (Ropeobj177006*)0; LOC42 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_505), LOC41, 0); add_177482_2381377266(&pl0, LOC42); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); genassignment_537264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA19: ; } goto LA8; LA11: ; { TY531289 LOC44; Ropeobj177006* LOC45; memset((void*)LOC44, 0, sizeof(LOC44)); LOC45 = (Ropeobj177006*)0; LOC45 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_117), LOC44, 0); add_177482_2381377266(&pl0, LOC45); { NIM_BOOL LOC48; NIM_BOOL LOC49; LOC48 = (NIM_BOOL)0; LOC49 = (NIM_BOOL)0; LOC49 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC49) goto LA50; LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA50: ; LOC48 = LOC49; if (!(LOC48)) goto LA51; LOC48 = (((*d0).flags &(1U<<((NU)(((Tlocflag290810) 8))&15U)))!=0); LA51: ; if (!LOC48) goto LA52; (*d0).k = ((Tlockind290808) 9); unsureAsgnRef((void**) (&(*d0).r), pl0); (*d0).flags &= ~(((NU16)1) << ((((Tlocflag290810) 8)) % (sizeof(NU16)*8))); } goto LA46; LA52: ; { Tloc290816 list0; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA57; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA57: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_530273_839829468((&list0), ((Tlockind290808) 9), (*d0).t, ((Tstorageloc290812) 0)); list0.r = pl0; genassignment_537264_839829468(p0, (&(*d0)), (&list0), 0); } LA46: ; } LA8: ; } goto LA4; LA6: ; { TY531289 LOC60; Ropeobj177006* LOC61; memset((void*)LOC60, 0, sizeof(LOC60)); LOC61 = (Ropeobj177006*)0; LOC61 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_505), LOC60, 0); add_177482_2381377266(&pl0, LOC61); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); } LA4: ; } N_NIMCALL(void, geninfixcall_539929_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) { Tloc290816 op0; Ttype290840* typ_539940_839829468; NI length0; NimStringDesc* pat0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); typ_539940_839829468 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_293351_850551059(ri0); pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data; { NimStringDesc* LOC5; if (!!(!((pat0 == NIM_NIL)))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_194185_1689653243(T839829468_498); internalerror_194113_155036129(LOC5); } LA3: ; { NIM_BOOL LOC8; Ropeobj177006* pl0; Ttype290840* typ0; LOC8 = (NIM_BOOL)0; LOC8 = contains_109056_4286263276(pat0, T839829468_500); if (!LOC8) goto LA9; pl0 = genpatterncall_539699_839829468(p0, ri0, pat0, typ_539940_839829468); typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA13; { NIM_BOOL LOC17; NIM_BOOL LOC18; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC18) goto LA19; LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA19: ; LOC17 = LOC18; if (!(LOC17)) goto LA20; LOC17 = (((*d0).flags &(1U<<((NU)(((Tlocflag290810) 8))&15U)))!=0); LA20: ; if (!LOC17) goto LA21; (*d0).k = ((Tlockind290808) 9); unsureAsgnRef((void**) (&(*d0).r), pl0); (*d0).flags &= ~(((NU16)1) << ((((Tlocflag290810) 8)) % (sizeof(NU16)*8))); } goto LA15; LA21: ; { Tloc290816 list0; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA26; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA26: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_530273_839829468((&list0), ((Tlockind290808) 9), (*d0).t, ((Tstorageloc290812) 0)); list0.r = pl0; genassignment_537264_839829468(p0, (&(*d0)), (&list0), 0); } LA15: ; } goto LA11; LA13: ; { TY531289 LOC29; Ropeobj177006* LOC30; memset((void*)LOC29, 0, sizeof(LOC29)); LOC30 = (Ropeobj177006*)0; LOC30 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_497), LOC29, 0); add_177482_2381377266(&pl0, LOC30); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); } LA11: ; } goto LA6; LA9: ; { Ropeobj177006* pl0; Ropeobj177006* params0; pl0 = NIM_NIL; { NI LOC34; Ropeobj177006* LOC37; LOC34 = (NI)0; LOC34 = len_291081_850551059(ri0); if (!(((NI) 1) < LOC34)) goto LA35; LOC37 = (Ropeobj177006*)0; LOC37 = genthisarg_539475_839829468(p0, ri0, ((NI) 1), typ_539940_839829468); add_177482_2381377266(&pl0, LOC37); } LA35: ; add_177482_2381377266(&pl0, op0.r); params0 = (Ropeobj177006*)0; { NI i_540425_839829468; NI HEX3Atmp_540609_839829468; NI res_540612_839829468; i_540425_839829468 = (NI)0; HEX3Atmp_540609_839829468 = (NI)0; HEX3Atmp_540609_839829468 = (NI)(length0 - ((NI) 1)); res_540612_839829468 = ((NI) 2); { while (1) { Ropeobj177006* LOC47; if (!(res_540612_839829468 <= HEX3Atmp_540609_839829468)) goto LA40; i_540425_839829468 = res_540612_839829468; { TY531289 LOC45; Ropeobj177006* LOC46; if (!!((params0 == NIM_NIL))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (Ropeobj177006*)0; LOC46 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC45, 0); add_177482_2381377266(&params0, LOC46); } LA43: ; LOC47 = (Ropeobj177006*)0; LOC47 = genotherarg_537277_839829468(p0, ri0, i_540425_839829468, typ_539940_839829468); add_177482_2381377266(&params0, LOC47); res_540612_839829468 += ((NI) 1); } LA40: ; } } fixupcall_537410_839829468(p0, le0, ri0, d0, pl0, params0); } LA6: ; } N_NIMCALL(void, gennamedparamcall_540616_839829468)(Tcproc527021* p0, Tnode290802* ri0, Tloc290816* d0) { Tloc290816 op0; Ropeobj177006* pl0; TY531289 LOC1; Ttype290840* typ0; NI length0; NimStringDesc* pat0; NI start0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); memset((void*)LOC1, 0, sizeof(LOC1)); pl0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_506), LOC1, 0); typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_293351_850551059(ri0); pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data; { NimStringDesc* LOC6; if (!!(!((pat0 == NIM_NIL)))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_194185_1689653243(T839829468_507); internalerror_194113_155036129(LOC6); } LA4: ; start0 = ((NI) 3); { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = contains_109046_4286263276(pat0, 32); if (!LOC9) goto LA10; start0 = ((NI) 1); add_177482_2381377266(&pl0, op0.r); { TY531289 LOC16; Ropeobj177006* LOC17; Ropeobj177006* LOC18; if (!(((NI) 1) < length0)) goto LA14; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (Ropeobj177006*)0; LOC17 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_244), LOC16, 0); add_177482_2381377266(&pl0, LOC17); LOC18 = (Ropeobj177006*)0; LOC18 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0); add_177482_2381377266(&pl0, LOC18); start0 = ((NI) 2); } LA14: ; } goto LA7; LA10: ; { { Ropeobj177006* LOC24; TY531289 LOC25; Ropeobj177006* LOC26; if (!(((NI) 1) < length0)) goto LA22; LOC24 = (Ropeobj177006*)0; LOC24 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0); add_177482_2381377266(&pl0, LOC24); memset((void*)LOC25, 0, sizeof(LOC25)); LOC26 = (Ropeobj177006*)0; LOC26 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC25, 0); add_177482_2381377266(&pl0, LOC26); } LA22: ; add_177482_2381377266(&pl0, op0.r); { TY531289 LOC31; Ropeobj177006* LOC32; Ropeobj177006* LOC33; if (!(((NI) 2) < length0)) goto LA29; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj177006*)0; LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_244), LOC31, 0); add_177482_2381377266(&pl0, LOC32); LOC33 = (Ropeobj177006*)0; LOC33 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 2)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 2)]).kindU.S4.sym, ri0); add_177482_2381377266(&pl0, LOC33); } LA29: ; } LA7: ; { NI i_541051_839829468; NI HEX3Atmp_541617_839829468; NI res_541620_839829468; i_541051_839829468 = (NI)0; HEX3Atmp_541617_839829468 = (NI)0; HEX3Atmp_541617_839829468 = (NI)(length0 - ((NI) 1)); res_541620_839829468 = start0; { while (1) { Tsym290834* param0; TY531289 LOC42; Ropeobj177006* LOC43; TY531289 LOC44; Ropeobj177006* LOC45; Ropeobj177006* LOC46; if (!(res_541620_839829468 <= HEX3Atmp_541617_839829468)) goto LA36; i_541051_839829468 = res_541620_839829468; { NI LOC39; LOC39 = (NI)0; LOC39 = sonslen_293327_850551059(typ0); if (!(LOC39 <= i_541051_839829468)) goto LA40; internalerror_194100_155036129((*ri0).info, ((NimStringDesc*) &T839829468_508)); } LA40: ; param0 = (*(*(*typ0).n).kindU.S6.sons->data[i_541051_839829468]).kindU.S4.sym; memset((void*)LOC42, 0, sizeof(LOC42)); LOC43 = (Ropeobj177006*)0; LOC43 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC42, 0); add_177482_2381377266(&pl0, LOC43); add_177487_2381377266(&pl0, (*(*param0).name).s); memset((void*)LOC44, 0, sizeof(LOC44)); LOC45 = (Ropeobj177006*)0; LOC45 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_244), LOC44, 0); add_177482_2381377266(&pl0, LOC45); LOC46 = (Ropeobj177006*)0; LOC46 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[i_541051_839829468], param0, ri0); add_177482_2381377266(&pl0, LOC46); res_541620_839829468 += ((NI) 1); } LA36: ; } } { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA49; { NIM_BOOL LOC53; LOC53 = (NIM_BOOL)0; LOC53 = isinvalidreturntype_531550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC53) goto LA54; { NI LOC58; TY531289 LOC61; Ropeobj177006* LOC62; LOC58 = (NI)0; LOC58 = sonslen_293351_850551059(ri0); if (!(((NI) 1) < LOC58)) goto LA59; memset((void*)LOC61, 0, sizeof(LOC61)); LOC62 = (Ropeobj177006*)0; LOC62 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC61, 0); add_177482_2381377266(&pl0, LOC62); } LA59: ; { TY531289 LOC71; Ropeobj177006* LOC72; Ropeobj177006* LOC73; TY531289 LOC74; Ropeobj177006* LOC75; if (!((3 &(1U<<((NU)((*d0).k)&15U)))!=0)) goto LA65; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA69; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } LA69: ; memset((void*)LOC71, 0, sizeof(LOC71)); LOC72 = (Ropeobj177006*)0; LOC72 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_509), LOC71, 0); add_177482_2381377266(&pl0, LOC72); LOC73 = (Ropeobj177006*)0; LOC73 = addrloc_536204_839829468((&(*d0))); add_177482_2381377266(&pl0, LOC73); memset((void*)LOC74, 0, sizeof(LOC74)); LOC75 = (Ropeobj177006*)0; LOC75 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_510), LOC74, 0); add_177482_2381377266(&pl0, LOC75); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); } goto LA63; LA65: ; { Tloc290816 tmp0; Ropeobj177006* LOC77; TY531289 LOC78; Ropeobj177006* LOC79; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC77 = (Ropeobj177006*)0; LOC77 = addrloc_536204_839829468((&tmp0)); add_177482_2381377266(&pl0, LOC77); memset((void*)LOC78, 0, sizeof(LOC78)); LOC79 = (Ropeobj177006*)0; LOC79 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_510), LOC78, 0); add_177482_2381377266(&pl0, LOC79); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); genassignment_537264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA63: ; } goto LA51; LA54: ; { TY531289 LOC81; Ropeobj177006* LOC82; Tloc290816 list0; memset((void*)LOC81, 0, sizeof(LOC81)); LOC82 = (Ropeobj177006*)0; LOC82 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_511), LOC81, 0); add_177482_2381377266(&pl0, LOC82); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA85; gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA85: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_530273_839829468((&list0), ((Tlockind290808) 9), NIM_NIL, ((Tstorageloc290812) 0)); list0.r = pl0; genassignment_537264_839829468(p0, (&(*d0)), (&list0), 0); } LA51: ; } goto LA47; LA49: ; { TY531289 LOC88; Ropeobj177006* LOC89; memset((void*)LOC88, 0, sizeof(LOC88)); LOC89 = (Ropeobj177006*)0; LOC89 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_510), LOC88, 0); add_177482_2381377266(&pl0, LOC89); line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0); } LA47: ; } N_NIMCALL(void, genprefixcall_537960_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) { Tloc290816 op0; Ropeobj177006* params0; Ttype290840* typ0; NI length0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); params0 = (Ropeobj177006*)0; typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_293351_850551059(ri0); { NI i_538213_839829468; NI HEX3Atmp_538445_839829468; NI res_538448_839829468; i_538213_839829468 = (NI)0; HEX3Atmp_538445_839829468 = (NI)0; HEX3Atmp_538445_839829468 = (NI)(length0 - ((NI) 1)); res_538448_839829468 = ((NI) 1); { while (1) { if (!(res_538448_839829468 <= HEX3Atmp_538445_839829468)) goto LA3; i_538213_839829468 = res_538448_839829468; { NI LOC6; Tnode290802* paramtype0; LOC6 = (NI)0; LOC6 = sonslen_293327_850551059(typ0); if (!(i_538213_839829468 < LOC6)) goto LA7; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_538213_839829468]; { NIM_BOOL LOC11; Ropeobj177006* LOC20; LOC11 = (NIM_BOOL)0; LOC11 = iscompiletimeonly_326706_3876443242((*paramtype0).typ); if (!!(LOC11)) goto LA12; { TY531289 LOC18; Ropeobj177006* LOC19; if (!!((params0 == NIM_NIL))) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (Ropeobj177006*)0; LOC19 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0); add_177482_2381377266(&params0, LOC19); } LA16: ; LOC20 = (Ropeobj177006*)0; LOC20 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[i_538213_839829468], (*paramtype0).kindU.S4.sym, ri0); add_177482_2381377266(&params0, LOC20); } LA12: ; } goto LA4; LA7: ; { Ropeobj177006* LOC28; { TY531289 LOC26; Ropeobj177006* LOC27; if (!!((params0 == NIM_NIL))) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC27 = (Ropeobj177006*)0; LOC27 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0); add_177482_2381377266(&params0, LOC27); } LA24: ; LOC28 = (Ropeobj177006*)0; LOC28 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i_538213_839829468]); add_177482_2381377266(&params0, LOC28); } LA4: ; res_538448_839829468 += ((NI) 1); } LA3: ; } } fixupcall_537410_839829468(p0, le0, ri0, d0, op0.r, params0); } static N_INLINE(void, poststmtactions_530942_839829468)(Tcproc527021* p0) { Ropeobj177006** LOC1; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(LOC1, (*(*p0).module).injectstmt); } N_NIMCALL(void, gencall_541632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { { Ttype290840* LOC3; LOC3 = (Ttype290840*)0; LOC3 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, 2048); if (!((*LOC3).callconv == ((Tcallingconvention290002) 8))) goto LA4; genclosurecall_538452_839829468(p0, NIM_NIL, e0, d0); } goto LA1; LA4: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC7)) goto LA8; LOC7 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; geninfixcall_539929_839829468(p0, NIM_NIL, e0, d0); } goto LA1; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC12)) goto LA13; LOC12 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 28))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; gennamedparamcall_540616_839829468(p0, e0, d0); } goto LA1; LA14: ; { genprefixcall_537960_839829468(p0, NIM_NIL, e0, d0); } LA1: ; poststmtactions_530942_839829468(p0); } N_NIMCALL(void, genreset_552731_839829468)(Tcproc527021* p0, Tnode290802* n0) { Tloc290816 a0; TY530811 LOC1; Ttype290840* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = addrloc_536204_839829468((&a0)); LOC2 = (Ttype290840*)0; LOC2 = skiptypes_294099_850551059(a0.t, IL64(211106242013440)); LOC1[1] = gentypeinfo_533941_839829468((*p0).module, LOC2); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_496), LOC1, 2); } N_NIMCALL(void, genecho_552369_839829468)(Tcproc527021* p0, Tnode290802* n0) { NIM_BOOL LOC6; Ropeobj177006* args0; Tloc290816 a0; TY530811 LOC18; NimStringDesc* LOC19; NI LOC20; NimStringDesc* LOC21; TY531289 LOC22; { NimStringDesc* LOC5; if (!!(((*n0).kind == ((Tnodekind290020) 41)))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_194185_1689653243(T839829468_512); internalerror_194113_155036129(LOC5); } LA3: ; LOC6 = (NIM_BOOL)0; LOC6 = includestr_147249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_513)); args0 = NIM_NIL; memset((void*)(&a0), 0, sizeof(a0)); { NI i_552404_839829468; NI HEX3Atmp_552431_839829468; NI LOC8; NI res_552434_839829468; i_552404_839829468 = (NI)0; HEX3Atmp_552431_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = len_291081_850551059(n0); HEX3Atmp_552431_839829468 = (NI)(LOC8 - ((NI) 1)); res_552434_839829468 = ((NI) 0); { while (1) { if (!(res_552434_839829468 <= HEX3Atmp_552431_839829468)) goto LA10; i_552404_839829468 = res_552434_839829468; { Tnode290802* LOC13; LOC13 = (Tnode290802*)0; LOC13 = skipconv_326882_3876443242((*n0).kindU.S6.sons->data[i_552404_839829468]); if (!((*LOC13).kind == ((Tnodekind290020) 23))) goto LA14; add_177487_2381377266(&args0, ((NimStringDesc*) &T839829468_514)); } goto LA11; LA14: ; { TY177507 LOC17; initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[i_552404_839829468], (&a0)); memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_536188_839829468((&a0)); addf_178205_2381377266(&args0, ((NimStringDesc*) &T839829468_515), LOC17, 1); } LA11: ; res_552434_839829468 += ((NI) 1); } LA10: ; } } memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (NimStringDesc*)0; LOC20 = (NI)0; LOC20 = len_291081_850551059(n0); LOC21 = (NimStringDesc*)0; LOC21 = nsuRepeatStr(((NimStringDesc*) &T839829468_517), ((NI) (LOC20))); LOC19 = rawNewString(LOC21->Sup.len + tnl_175644_4151366050->Sup.len + 0); appendString(LOC19, LOC21); appendString(LOC19, tnl_175644_4151366050); LOC18[0] = makecstring_189638_155036129(LOC19); LOC18[1] = args0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_516), LOC18, 2); memset((void*)LOC22, 0, sizeof(LOC22)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_518), LOC22, 0); } N_NIMCALL(void, genseqconstr_553004_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) { Tloc290816 arr0; NI LOC5; Ropeobj177006* LOC6; memset((void*)(&arr0), 0, sizeof(arr0)); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA3; gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA3: ; LOC5 = (NI)0; LOC5 = sonslen_293351_850551059(t0); LOC6 = (Ropeobj177006*)0; LOC6 = intliteral_537270_839829468(((NI64) (LOC5))); gennewseqaux_552795_839829468(p0, (&(*d0)), LOC6); { NI i_553031_839829468; NI HEX3Atmp_553039_839829468; NI LOC8; NI res_553042_839829468; i_553031_839829468 = (NI)0; HEX3Atmp_553039_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = sonslen_293351_850551059(t0); HEX3Atmp_553039_839829468 = (NI)(LOC8 - ((NI) 1)); res_553042_839829468 = ((NI) 0); { while (1) { Ttype290840* LOC11; Ttype290840* LOC12; TY530811 LOC13; if (!(res_553042_839829468 <= HEX3Atmp_553039_839829468)) goto LA10; i_553031_839829468 = res_553042_839829468; LOC11 = (Ttype290840*)0; LOC11 = skiptypes_294099_850551059((*t0).typ, IL64(211106232576256)); LOC12 = (Ttype290840*)0; LOC12 = elemtype_318394_3876443242(LOC11); initloc_530273_839829468((&arr0), ((Tlockind290808) 6), LOC12, ((Tstorageloc290812) 3)); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = rdloc_536188_839829468((&(*d0))); LOC13[1] = intliteral_537270_839829468(((NI64) (i_553031_839829468))); arr0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC13, 2); arr0.s = ((Tstorageloc290812) 3); expr_537248_839829468(p0, (*t0).kindU.S6.sons->data[i_553031_839829468], (&arr0)); res_553042_839829468 += ((NI) 1); } LA10: ; } } gcusage_552439_839829468(t0); } N_NIMCALL(void, genarrtoseq_553046_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) { Tloc290816 elem0; Tloc290816 a0; Tloc290816 arr0; NI L0; NI64 LOC9; Ropeobj177006* LOC10; { memset((void*)(&elem0), 0, sizeof(elem0)); memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&arr0), 0, sizeof(arr0)); { if (!((*t0).kind == ((Tnodekind290020) 41))) goto LA3; asgnRefNoCycle((void**) (&(*(*t0).kindU.S6.sons->data[((NI) 1)]).typ), (*t0).typ); genseqconstr_553004_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], d0); goto BeforeRet; } LA3: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA7; gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA7: ; LOC9 = (NI64)0; LOC9 = lengthord_318007_3876443242((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ); L0 = ((NI) (LOC9)); LOC10 = (Ropeobj177006*)0; LOC10 = intliteral_537270_839829468(((NI64) (L0))); gennewseqaux_552795_839829468(p0, (&(*d0)), LOC10); initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], (&a0)); { NI i_553090_839829468; NI HEX3Atmp_553104_839829468; NI res_553107_839829468; i_553090_839829468 = (NI)0; HEX3Atmp_553104_839829468 = (NI)0; HEX3Atmp_553104_839829468 = (NI)(L0 - ((NI) 1)); res_553107_839829468 = ((NI) 0); { while (1) { Ttype290840* LOC14; Ttype290840* LOC15; TY530811 LOC16; Ttype290840* LOC17; Ttype290840* LOC18; TY530811 LOC19; if (!(res_553107_839829468 <= HEX3Atmp_553104_839829468)) goto LA13; i_553090_839829468 = res_553107_839829468; LOC14 = (Ttype290840*)0; LOC14 = skiptypes_294099_850551059((*t0).typ, IL64(211106232576256)); LOC15 = (Ttype290840*)0; LOC15 = elemtype_318394_3876443242(LOC14); initloc_530273_839829468((&elem0), ((Tlockind290808) 6), LOC15, ((Tstorageloc290812) 3)); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_536188_839829468((&(*d0))); LOC16[1] = intliteral_537270_839829468(((NI64) (i_553090_839829468))); elem0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC16, 2); elem0.s = ((Tstorageloc290812) 3); LOC17 = (Ttype290840*)0; LOC17 = skiptypes_294099_850551059((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106232576256)); LOC18 = (Ttype290840*)0; LOC18 = elemtype_318394_3876443242(LOC17); initloc_530273_839829468((&arr0), ((Tlockind290808) 6), LOC18, a0.s); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_536188_839829468((&a0)); LOC19[1] = intliteral_537270_839829468(((NI64) (i_553090_839829468))); arr0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC19, 2); genassignment_537264_839829468(p0, (&elem0), (&arr0), 3); res_553107_839829468 += ((NI) 1); } LA13: ; } } }BeforeRet: ; } N_NIMCALL(void, gendeepcopy_548374_839829468)(Tcproc527021* p0, Tloc290816* dest0, Tloc290816* src0) { Ttype290840* ty0; ty0 = skiptypes_294099_850551059((*dest0).t, IL64(211106242013440)); switch ((*ty0).kind) { case ((Ttypekind290244) 21): case ((Ttypekind290244) 22): case ((Ttypekind290244) 25): case ((Ttypekind290244) 18): case ((Ttypekind290244) 17): case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { TY533238 LOC2; memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = addrloc_536204_839829468(dest0); LOC2[1] = addrloc_536204_839829468(src0); LOC2[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_519), LOC2, 3); } break; case ((Ttypekind290244) 24): case ((Ttypekind290244) 28): { TY533238 LOC4; memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = addrloc_536204_839829468(dest0); LOC4[1] = rdloc_536188_839829468(src0); LOC4[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_520), LOC4, 3); } break; case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { TY533238 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = addrloc_536204_839829468(dest0); LOC6[1] = addrloc_536204_839829468(src0); LOC6[2] = gentypeinfo_533941_839829468((*p0).module, (*dest0).t); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_521), LOC6, 3); } break; case ((Ttypekind290244) 19): { { Tctypekind527007 LOC10; TY533238 LOC13; NI64 LOC14; LOC10 = (Tctypekind527007)0; LOC10 = maptype_531394_839829468(ty0); if (!(LOC10 == ((Tctypekind527007) 17))) goto LA11; usestringh_530345_839829468((*p0).module); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = rdloc_536188_839829468(dest0); LOC13[1] = rdloc_536188_839829468(src0); LOC14 = (NI64)0; LOC14 = getsize_318135_3876443242((*dest0).t); LOC13[2] = rope_177401_2381377266(LOC14); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_268), LOC13, 3); } goto LA8; LA11: ; { TY530811 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_536188_839829468(dest0); LOC16[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC16, 2); } LA8: ; } break; case ((Ttypekind290244) 26): case ((Ttypekind290244) 2): case ((Ttypekind290244) 1): case ((Ttypekind290244) 14): case ((Ttypekind290244) 29): case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44): case ((Ttypekind290244) 20): case ((Ttypekind290244) 23): { TY530811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_536188_839829468(dest0); LOC18[1] = rdloc_536188_839829468(src0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC18, 2); } break; default: { NimStringDesc* LOC20; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI290244))->Sup.len + 13); appendString(LOC20, ((NimStringDesc*) &T839829468_522)); appendString(LOC20, reprEnum((NI)(*ty0).kind, (&NTI290244))); internalerror_194113_155036129(LOC20); } break; } } N_NIMCALL(void, genmagicexpr_555033_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) { switch (op0) { case ((Tmagic290524) 127): case ((Tmagic290524) 126): { genandor_552311_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 99) ... ((Tmagic290524) 117): { unaryarith_550646_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 96) ... ((Tmagic290524) 98): { unaryarithoverflow_549633_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 52) ... ((Tmagic290524) 55): { binaryfloatarith_554729_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 56) ... ((Tmagic290524) 93): { binaryarith_549819_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 95): { geneqproc_550214_839829468(p0, e0, d0); } break; case ((Tmagic290524) 45) ... ((Tmagic290524) 51): { binaryarithoverflow_549262_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 149): { genrepr_553339_839829468(p0, e0, d0); } break; case ((Tmagic290524) 259): { gengettypeinfo_553383_839829468(p0, e0, d0); } break; case ((Tmagic290524) 156): { genswap_553638_839829468(p0, e0, d0); } break; case ((Tmagic290524) 25): { { if (!!((((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0))) goto LA14; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_385)); } goto LA12; LA14: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_386)); } LA12: ; } break; case ((Tmagic290524) 26): case ((Tmagic290524) 27): { Ttype290840* underlying0; underlying0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 9439232); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = !((((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0)); if (LOC20) goto LA21; LOC20 = ((IL64(34084860461056) &((NU64)1<<((NU)((*underlying0).kind)&63U)))!=0); LA21: ; if (!LOC20) goto LA22; binarystmt_548501_839829468(p0, e0, d0, opr_555050_839829468[(op0)- 26]); } goto LA18; LA22: ; { Tloc290816 a0; Tloc290816 b0; Ttype290840* ranged0; Ropeobj177006* res0; NimStringDesc* LOC25; TY530811 LOC31; Ropeobj177006* LOC32; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); ranged0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 8390656); LOC25 = (NimStringDesc*)0; { if (!((*underlying0).kind == ((Ttypekind290244) 35))) goto LA28; LOC25 = copyString(fun64_555055_839829468[(op0)- 26]); } goto LA26; LA28: ; { LOC25 = copyString(fun_555060_839829468[(op0)- 26]); } LA26: ; res0 = binaryarithoverflowraw_549235_839829468(p0, ranged0, (&a0), (&b0), LOC25); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = gettypedesc_533673_839829468((*p0).module, ranged0); LOC31[1] = res0; LOC32 = (Ropeobj177006*)0; LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_370), LOC31, 2); putintodest_548468_839829468(p0, (&a0), ranged0, LOC32, ((Tstorageloc290812) 0)); } LA18: ; } break; case ((Tmagic290524) 138): { genstrconcat_552452_839829468(p0, e0, d0); } break; case ((Tmagic290524) 144): { binarystmt_548501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_394)); } break; case ((Tmagic290524) 145): { genstrappend_552554_839829468(p0, e0, d0); } break; case ((Tmagic290524) 146): { genseqelemappend_552683_839829468(p0, e0, d0); } break; case ((Tmagic290524) 128): { genstrequals_554667_839829468(p0, e0, d0); } break; case ((Tmagic290524) 129): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_402)); } break; case ((Tmagic290524) 130): { binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_403)); } break; case ((Tmagic290524) 157): { genisnil_550620_839829468(p0, e0, d0); } break; case ((Tmagic290524) 120): { gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_406)); } break; case ((Tmagic290524) 121): { gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_407)); } break; case ((Tmagic290524) 119): { gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_408)); } break; case ((Tmagic290524) 118): { gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_409)); } break; case ((Tmagic290524) 122): { gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_410)); } break; case ((Tmagic290524) 123): { gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_411)); } break; case ((Tmagic290524) 124): { expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Tmagic290524) 125): { genrepr_553339_839829468(p0, e0, d0); } break; case ((Tmagic290524) 12): { genof_553331_839829468(p0, e0, d0); } break; case ((Tmagic290524) 29): { gennew_552782_839829468(p0, e0); } break; case ((Tmagic290524) 30): { gennewfinalize_553111_839829468(p0, e0); } break; case ((Tmagic290524) 31): { gennewseq_552824_839829468(p0, e0); } break; case ((Tmagic290524) 32): { gennewseqofcap_552836_839829468(p0, e0, d0); } break; case ((Tmagic290524) 9): { Ttype290840* t0; TY177507 LOC55; Ropeobj177006* LOC56; t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 256); memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC56 = (Ropeobj177006*)0; LOC56 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_428), LOC55, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC56, ((Tstorageloc290812) 0)); } break; case ((Tmagic290524) 42): { gensomecast_554481_839829468(p0, e0, d0); } break; case ((Tmagic290524) 28): { genord_554475_839829468(p0, e0, d0); } break; case ((Tmagic290524) 35): case ((Tmagic290524) 8): case ((Tmagic290524) 34): case ((Tmagic290524) 36): case ((Tmagic290524) 33): { genarraylen_553415_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 37): case ((Tmagic290524) 38): { { NIM_BOOL LOC63; LOC63 = (NIM_BOOL)0; LOC63 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC63) goto LA64; LOC63 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA64: ; if (!!(LOC63)) goto LA65; unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_440)); } goto LA61; LA65: ; { unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_441)); } LA61: ; } break; case ((Tmagic290524) 43): { unarystmt_548527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_443)); } break; case ((Tmagic290524) 44): { unarystmt_548527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_444)); } break; case ((Tmagic290524) 151): { gensetlengthstr_553632_839829468(p0, e0, d0); } break; case ((Tmagic290524) 152): { gensetlengthseq_553500_839829468(p0, e0, d0); } break; case ((Tmagic290524) 39): case ((Tmagic290524) 40): case ((Tmagic290524) 41): case ((Tmagic290524) 133): case ((Tmagic290524) 132): case ((Tmagic290524) 131): case ((Tmagic290524) 134): case ((Tmagic290524) 135): case ((Tmagic290524) 136): case ((Tmagic290524) 148): { gensetop_554419_839829468(p0, e0, d0, op0); } break; case ((Tmagic290524) 161): case ((Tmagic290524) 162): case ((Tmagic290524) 159): case ((Tmagic290524) 160): case ((Tmagic290524) 150): case ((Tmagic290524) 163): { Tsym290834* opr0; opr0 = (*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NimStringDesc* LOC78; Ropeobj177006* LOC79; if (!!((((*opr0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0))) goto LA76; LOC78 = (NimStringDesc*)0; LOC78 = HEX24_177856_2381377266((*opr0).loc.r); LOC79 = (Ropeobj177006*)0; LOC79 = cgsym_530403_839829468((*p0).module, LOC78); } LA76: ; gencall_541632_839829468(p0, e0, d0); } break; case ((Tmagic290524) 164): { genreset_552731_839829468(p0, e0); } break; case ((Tmagic290524) 17): { Tnode290802* LOC82; Tnode290802* LOC83; LOC82 = (Tnode290802*)0; LOC82 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1)); LOC83 = (Tnode290802*)0; LOC83 = skipconv_326882_3876443242(LOC82); genecho_552369_839829468(p0, LOC83); } break; case ((Tmagic290524) 158): { genarrtoseq_553046_839829468(p0, e0, d0); } break; case ((Tmagic290524) 223) ... ((Tmagic290524) 257): case ((Tmagic290524) 19) ... ((Tmagic290524) 24): { localerror_194080_155036129((*e0).info, ((Tmsgkind189002) 229), (*(*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s); } break; case ((Tmagic290524) 208): { Tnode290802* n0; n0 = wrapprocforspawn_433501_2218250499((*(*p0).module).module, e0, (*e0).typ, NIM_NIL, NIM_NIL); expr_537248_839829468(p0, n0, d0); } break; case ((Tmagic290524) 155): { Tnode290802* n0; n0 = liftparallel_476822_1773027539((*(*p0).module).module, e0); expr_537248_839829468(p0, n0, d0); } break; case ((Tmagic290524) 209): { Tloc290816 a0; Tloc290816 b0; Tnode290802* x0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); { Tnode290802* LOC91; Tnode290802* LOC94; LOC91 = (Tnode290802*)0; LOC91 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1)); if (!((*LOC91).kind == ((Tnodekind290020) 63) || (*LOC91).kind == ((Tnodekind290020) 64))) goto LA92; LOC94 = (Tnode290802*)0; LOC94 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1)); x0 = HEX5BHEX5D_291238_850551059(LOC94, ((NI) 0)); } goto LA89; LA92: ; { x0 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1)); } LA89: ; initlocexpr_537283_839829468(p0, x0, (&a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); gendeepcopy_548374_839829468(p0, (&a0), (&b0)); } break; case ((Tmagic290524) 140): case ((Tmagic290524) 94): { gencall_541632_839829468(p0, e0, d0); } break; default: { NimStringDesc* LOC98; LOC98 = (NimStringDesc*)0; LOC98 = rawNewString(reprEnum((NI)op0, (&NTI290524))->Sup.len + 14); appendString(LOC98, ((NimStringDesc*) &T839829468_523)); appendString(LOC98, reprEnum((NI)op0, (&NTI290524))); internalerror_194100_155036129((*e0).info, LOC98); } break; } } N_NIMCALL(Ropeobj177006*, gensetnode_547664_839829468)(Tcproc527021* p0, Tnode290802* n0) { Ropeobj177006* result0; Tbitset337004* cs0; NI size0; NI64 LOC1; result0 = (Ropeobj177006*)0; cs0 = (Tbitset337004*)0; LOC1 = (NI64)0; LOC1 = getsize_318135_3876443242((*n0).typ); size0 = ((NI) (LOC1)); tobitset_338001_452470228(n0, (&cs0)); { NI id0; Ropeobj177006* LOC6; if (!(((NI) 8) < size0)) goto LA4; id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC6 = (Ropeobj177006*)0; LOC6 = rope_177401_2381377266(((NI64) (id0))); result0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC6); { TY533238 LOC11; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA9; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_533673_839829468((*p0).module, (*n0).typ); LOC11[1] = result0; LOC11[2] = genrawsetdata_547629_839829468(cs0, size0); addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC11, 3); } LA9: ; } goto LA2; LA4: ; { result0 = genrawsetdata_547629_839829468(cs0, size0); } LA2: ; return result0; } N_NIMCALL(void, gensetconstr_555496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Tloc290816 idx0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&idx0), 0, sizeof(idx0)); { Ropeobj177006* LOC5; if (!(((*e0).flags &(1U<<((NU)(((Tnodeflag290427) 4))&15U)))!=0)) goto LA3; LOC5 = (Ropeobj177006*)0; LOC5 = gensetnode_547664_839829468(p0, e0); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC5, ((Tstorageloc290812) 0)); } goto LA1; LA3: ; { { if (!((*d0).k == ((Tlockind290808) 0))) goto LA9; gettemp_535032_839829468(p0, (*e0).typ, d0, NIM_FALSE); } LA9: ; { NI64 LOC13; TY177507 LOC16; LOC13 = (NI64)0; LOC13 = getsize_318135_3876443242((*e0).typ); if (!(IL64(8) < LOC13)) goto LA14; usestringh_530345_839829468((*p0).module); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_536188_839829468((&(*d0))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_525), LOC16, 1); { NI i_555537_839829468; NI HEX3Atmp_555603_839829468; NI LOC18; NI res_555606_839829468; i_555537_839829468 = (NI)0; HEX3Atmp_555603_839829468 = (NI)0; LOC18 = (NI)0; LOC18 = sonslen_293351_850551059(e0); HEX3Atmp_555603_839829468 = (NI)(LOC18 - ((NI) 1)); res_555606_839829468 = ((NI) 0); { while (1) { if (!(res_555606_839829468 <= HEX3Atmp_555603_839829468)) goto LA20; i_555537_839829468 = res_555606_839829468; { Ttype290840* LOC25; TY533235 LOC26; if (!((*(*e0).kindU.S6.sons->data[i_555537_839829468]).kind == ((Tnodekind290020) 44))) goto LA23; LOC25 = (Ttype290840*)0; LOC25 = getsystype_336150_3937434831(((Ttypekind290244) 31)); gettemp_535032_839829468(p0, LOC25, (&idx0), NIM_FALSE); initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555537_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555537_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0)); memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rdloc_536188_839829468((&idx0)); LOC26[1] = rdloc_536188_839829468((&(*d0))); LOC26[2] = rdsetelemloc_553662_839829468((&a0), (*e0).typ); LOC26[3] = rdsetelemloc_553662_839829468((&b0), (*e0).typ); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_526), LOC26, 4); } goto LA21; LA23: ; { TY530811 LOC28; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[i_555537_839829468], (&a0)); memset((void*)LOC28, 0, sizeof(LOC28)); LOC28[0] = rdloc_536188_839829468((&(*d0))); LOC28[1] = rdsetelemloc_553662_839829468((&a0), (*e0).typ); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_527), LOC28, 2); } LA21: ; res_555606_839829468 += ((NI) 1); } LA20: ; } } } goto LA11; LA14: ; { NimStringDesc* ts0; NimStringDesc* LOC30; NI64 LOC31; NimStringDesc* LOC32; TY177507 LOC33; LOC30 = (NimStringDesc*)0; LOC31 = (NI64)0; LOC31 = getsize_318135_3876443242((*e0).typ); LOC32 = (NimStringDesc*)0; LOC32 = nimInt64ToStr((NI64)(LOC31 * IL64(8))); LOC30 = rawNewString(LOC32->Sup.len + 2); appendString(LOC30, ((NimStringDesc*) &T839829468_45)); appendString(LOC30, LOC32); ts0 = LOC30; memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rdloc_536188_839829468((&(*d0))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_494), LOC33, 1); { NI i_555575_839829468; NI HEX3Atmp_555611_839829468; NI LOC35; NI res_555614_839829468; i_555575_839829468 = (NI)0; HEX3Atmp_555611_839829468 = (NI)0; LOC35 = (NI)0; LOC35 = sonslen_293351_850551059(e0); HEX3Atmp_555611_839829468 = (NI)(LOC35 - ((NI) 1)); res_555614_839829468 = ((NI) 0); { while (1) { if (!(res_555614_839829468 <= HEX3Atmp_555611_839829468)) goto LA37; i_555575_839829468 = res_555614_839829468; { Ttype290840* LOC42; NimStringDesc* LOC43; TY533235 LOC44; if (!((*(*e0).kindU.S6.sons->data[i_555575_839829468]).kind == ((Tnodekind290020) 44))) goto LA40; LOC42 = (Ttype290840*)0; LOC42 = getsystype_336150_3937434831(((Ttypekind290244) 31)); gettemp_535032_839829468(p0, LOC42, (&idx0), NIM_FALSE); initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555575_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555575_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0)); LOC43 = (NimStringDesc*)0; LOC43 = rawNewString(ts0->Sup.len + ts0->Sup.len + 68); appendString(LOC43, ((NimStringDesc*) &T839829468_528)); appendString(LOC43, ts0); appendString(LOC43, ((NimStringDesc*) &T839829468_529)); appendString(LOC43, ts0); appendString(LOC43, ((NimStringDesc*) &T839829468_454)); memset((void*)LOC44, 0, sizeof(LOC44)); LOC44[0] = rdloc_536188_839829468((&idx0)); LOC44[1] = rdloc_536188_839829468((&(*d0))); LOC44[2] = rdsetelemloc_553662_839829468((&a0), (*e0).typ); LOC44[3] = rdsetelemloc_553662_839829468((&b0), (*e0).typ); linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC43, LOC44, 4); } goto LA38; LA40: ; { NimStringDesc* LOC46; TY530811 LOC47; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[i_555575_839829468], (&a0)); LOC46 = (NimStringDesc*)0; LOC46 = rawNewString(ts0->Sup.len + ts0->Sup.len + 36); appendString(LOC46, ((NimStringDesc*) &T839829468_530)); appendString(LOC46, ts0); appendString(LOC46, ((NimStringDesc*) &T839829468_531)); appendString(LOC46, ts0); appendString(LOC46, ((NimStringDesc*) &T839829468_454)); memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = rdloc_536188_839829468((&(*d0))); LOC47[1] = rdsetelemloc_553662_839829468((&a0), (*e0).typ); linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC46, LOC47, 2); } LA38: ; res_555614_839829468 += ((NI) 1); } LA37: ; } } } LA11: ; } LA1: ; } N_NIMCALL(void, exprcomplexconst_556684_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Ttype290840* t0; Ropeobj177006* LOC1; NI id0; Ropeobj177006* tmp0; Ropeobj177006* LOC2; t0 = getuniquetype_526640_2036603609((*n0).typ); LOC1 = (Ropeobj177006*)0; LOC1 = gettypedesc_533673_839829468((*p0).module, t0); id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC2 = (Ropeobj177006*)0; LOC2 = rope_177401_2381377266(((NI64) (id0))); tmp0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC2); { TY533238 LOC7; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA5; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC7[1] = tmp0; LOC7[2] = genconstexpr_552849_839829468(p0, n0); addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC7, 3); } LA5: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA10; fillloc_530282_839829468(d0, ((Tlockind290808) 8), t0, tmp0, ((Tstorageloc290812) 1)); } goto LA8; LA10: ; { putdataintodest_548436_839829468(p0, d0, t0, tmp0); { if (!!(((285212672 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0))) goto LA15; (*d0).s = ((Tstorageloc290812) 1); } LA15: ; } LA8: ; } N_NIMCALL(NIM_BOOL, handleconstexpr_552853_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; NI LOC6; Ttype290840* t0; Ropeobj177006* LOC10; NI id0; Ropeobj177006* LOC11; Ropeobj177006* LOC12; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = ((*d0).k == ((Tlockind290808) 0)); if (!(LOC4)) goto LA5; LOC6 = (NI)0; LOC6 = len_291081_850551059(n0); LOC4 = (((NI) (((*n0).kind == ((Tnodekind290020) 38)))) < LOC6); LA5: ; LOC3 = LOC4; if (!(LOC3)) goto LA7; LOC3 = isdeepconstexpr_316566_2616423590(n0); LA7: ; if (!LOC3) goto LA8; t0 = getuniquetype_526640_2036603609((*n0).typ); LOC10 = (Ropeobj177006*)0; LOC10 = gettypedesc_533673_839829468((*p0).module, t0); id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC11 = (Ropeobj177006*)0; LOC11 = rope_177401_2381377266(((NI64) (id0))); LOC12 = (Ropeobj177006*)0; LOC12 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC11); fillloc_530282_839829468(d0, ((Tlockind290808) 8), t0, LOC12, ((Tstorageloc290812) 1)); { TY533238 LOC17; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA15; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_533673_839829468((*p0).module, t0); LOC17[1] = (*d0).r; LOC17[2] = genconstexpr_552849_839829468(p0, n0); addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3); } LA15: ; result0 = NIM_TRUE; } goto LA1; LA8: ; { result0 = NIM_FALSE; } LA1: ; return result0; } N_NIMCALL(void, genarrayconstr_556207_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Tloc290816 arr0; memset((void*)(&arr0), 0, sizeof(arr0)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_552853_839829468(p0, n0, d0); if (!!(LOC3)) goto LA4; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA8; gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA8: ; { NI i_556234_839829468; NI HEX3Atmp_556242_839829468; NI LOC11; NI res_556245_839829468; i_556234_839829468 = (NI)0; HEX3Atmp_556242_839829468 = (NI)0; LOC11 = (NI)0; LOC11 = sonslen_293351_850551059(n0); HEX3Atmp_556242_839829468 = (NI)(LOC11 - ((NI) 1)); res_556245_839829468 = ((NI) 0); { while (1) { Ttype290840* LOC14; Ttype290840* LOC15; TY530811 LOC16; if (!(res_556245_839829468 <= HEX3Atmp_556242_839829468)) goto LA13; i_556234_839829468 = res_556245_839829468; LOC14 = (Ttype290840*)0; LOC14 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256)); LOC15 = (Ttype290840*)0; LOC15 = elemtype_318394_3876443242(LOC14); initloc_530273_839829468((&arr0), ((Tlockind290808) 6), LOC15, (*d0).s); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_536188_839829468((&(*d0))); LOC16[1] = intliteral_537270_839829468(((NI64) (i_556234_839829468))); arr0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_138), LOC16, 2); expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[i_556234_839829468], (&arr0)); res_556245_839829468 += ((NI) 1); } LA13: ; } } } LA4: ; } N_NIMCALL(void, gentupleconstr_555618_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Tloc290816 rec0; memset((void*)(&rec0), 0, sizeof(rec0)); { NIM_BOOL LOC3; Ttype290840* t0; Ropeobj177006* LOC6; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_552853_839829468(p0, n0, d0); if (!!(LOC3)) goto LA4; t0 = getuniquetype_526640_2036603609((*n0).typ); LOC6 = (Ropeobj177006*)0; LOC6 = gettypedesc_533673_839829468((*p0).module, t0); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA9; gettemp_535032_839829468(p0, t0, d0, NIM_FALSE); } LA9: ; { NI i_555646_839829468; NI HEX3Atmp_555803_839829468; NI LOC12; NI res_555806_839829468; i_555646_839829468 = (NI)0; HEX3Atmp_555803_839829468 = (NI)0; LOC12 = (NI)0; LOC12 = sonslen_293351_850551059(n0); HEX3Atmp_555803_839829468 = (NI)(LOC12 - ((NI) 1)); res_555806_839829468 = ((NI) 0); { while (1) { Tnode290802* it0; TY530811 LOC19; if (!(res_555806_839829468 <= HEX3Atmp_555803_839829468)) goto LA14; i_555646_839829468 = res_555806_839829468; it0 = (*n0).kindU.S6.sons->data[i_555646_839829468]; { if (!((*it0).kind == ((Tnodekind290020) 34))) goto LA17; it0 = (*it0).kindU.S6.sons->data[((NI) 1)]; } LA17: ; initloc_530273_839829468((&rec0), ((Tlockind290808) 6), (*it0).typ, (*d0).s); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_536188_839829468((&(*d0))); LOC19[1] = rope_177401_2381377266(((NI64) (i_555646_839829468))); rec0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_185), LOC19, 2); expr_537248_839829468(p0, it0, (&rec0)); res_555806_839829468 += ((NI) 1); } LA14: ; } } } LA4: ; } N_NIMCALL(Tsym290834*, lookupfieldagain_551154_839829468)(Tcproc527021* p0, Ttype290840* ty_551157_839829468, Tsym290834* field0, Ropeobj177006** r0) { Tsym290834* result0; Ttype290840* ty0; result0 = (Tsym290834*)0; ty0 = ty_551157_839829468; { while (1) { if (!!((ty0 == NIM_NIL))) goto LA2; ty0 = skiptypes_294099_850551059(ty0, IL64(211106247215360)); result0 = lookupinrecord_297119_2984716966((*ty0).n, (*field0).name); { if (!!((result0 == NIM_NIL))) goto LA5; goto LA1; } LA5: ; { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC9) goto LA10; LOC9 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA10: ; if (!!(LOC9)) goto LA11; add_177487_2381377266(r0, ((NimStringDesc*) &T839829468_153)); } LA11: ; ty0 = getuniquetype_526640_2036603609((*ty0).sons->data[((NI) 0)]); } LA2: ; } LA1: ; { if (!(result0 == NIM_NIL)) goto LA15; internalerror_194100_155036129((*field0).info, ((NimStringDesc*) &T839829468_532)); } LA15: ; return result0; } N_NIMCALL(void, genfieldcheck_551504_839829468)(Tcproc527021* p0, Tnode290802* e0, Ropeobj177006* obj0, Tsym290834* field0, Ttype290840* origty0) { Tloc290816 test0; Tloc290816 u0; Tloc290816 v0; memset((void*)(&test0), 0, sizeof(test0)); memset((void*)(&u0), 0, sizeof(u0)); memset((void*)(&v0), 0, sizeof(v0)); { NI i_551525_839829468; NI HEX3Atmp_552039_839829468; NI LOC2; NI res_552042_839829468; i_551525_839829468 = (NI)0; HEX3Atmp_552039_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(e0); HEX3Atmp_552039_839829468 = (NI)(LOC2 - ((NI) 1)); res_552042_839829468 = ((NI) 1); { while (1) { Tnode290802* it0; Tsym290834* op0; Tnode290802* disc0; Ropeobj177006* o0; Tsym290834* d0; NI id0; Tnode290802* LOC9; Ropeobj177006* strlit0; if (!(res_552042_839829468 <= HEX3Atmp_552039_839829468)) goto LA4; i_551525_839829468 = res_552042_839829468; it0 = (*e0).kindU.S6.sons->data[i_551525_839829468]; op0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { if (!((*op0).magic == ((Tmagic290524) 99))) goto LA7; it0 = (*it0).kindU.S6.sons->data[((NI) 1)]; } LA7: ; disc0 = skipconv_326882_3876443242((*it0).kindU.S6.sons->data[((NI) 2)]); initloc_530273_839829468((&test0), ((Tlockind290808) 0), (*it0).typ, ((Tstorageloc290812) 2)); initlocexpr_537283_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&u0)); o0 = obj0; d0 = lookupfieldagain_551154_839829468(p0, origty0, (*disc0).kindU.S4.sym, &o0); initloc_530273_839829468((&v0), ((Tlockind290808) 6), (*d0).typ, ((Tstorageloc290812) 0)); v0.r = o0; add_177487_2381377266(&v0.r, ((NimStringDesc*) &T839829468_257)); add_177482_2381377266(&v0.r, (*d0).loc.r); geninexpraux_551496_839829468(p0, it0, (&u0), (&v0), (&test0)); LOC9 = (Tnode290802*)0; LOC9 = newstrnode_291677_850551059(((Tnodekind290020) 20), (*(*field0).name).s); id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), LOC9, ((NI) ((*(*p0).module).labels))); { if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA12; strlit0 = getstrlit_547468_839829468((*p0).module, (*(*field0).name).s); } goto LA10; LA12: ; { Ropeobj177006* LOC15; LOC15 = (Ropeobj177006*)0; LOC15 = rope_177401_2381377266(((NI64) (id0))); strlit0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC15); } LA10: ; { TY530811 LOC20; if (!((*op0).magic == ((Tmagic290524) 99))) goto LA18; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rdloc_536188_839829468((&test0)); LOC20[1] = strlit0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_534), LOC20, 2); } goto LA16; LA18: ; { TY530811 LOC22; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = rdloc_536188_839829468((&test0)); LOC22[1] = strlit0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_535), LOC22, 2); } LA16: ; res_552042_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, genobjconstr_552903_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 tmp0; Ttype290840* t0; NIM_BOOL isref0; Ropeobj177006* r0; Ropeobj177006* LOC13; Ttype290840* ty0; { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_552853_839829468(p0, e0, d0); if (!LOC3) goto LA4; goto BeforeRet; } LA4: ; memset((void*)(&tmp0), 0, sizeof(tmp0)); t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106232576256)); gettemp_535032_839829468(p0, t0, (&tmp0), NIM_FALSE); isref0 = ((*t0).kind == ((Ttypekind290244) 22)); r0 = rdloc_536188_839829468((&tmp0)); { Ttype290840* LOC10; TY177507 LOC11; if (!isref0) goto LA8; rawgennew_552741_839829468(p0, (&tmp0), NIM_NIL); LOC10 = (Ttype290840*)0; LOC10 = lastson_293377_850551059(t0); t0 = skiptypes_294099_850551059(LOC10, IL64(211106232576256)); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = r0; r0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC11, 1); gcusage_552439_839829468(e0); } goto LA6; LA8: ; { constructloc_536388_839829468(p0, (&tmp0), NIM_FALSE); } LA6: ; LOC13 = (Ropeobj177006*)0; LOC13 = gettypedesc_533673_839829468((*p0).module, t0); ty0 = getuniquetype_526640_2036603609(t0); { NI i_552944_839829468; NI HEX3Atmp_552997_839829468; NI LOC15; NI res_553000_839829468; i_552944_839829468 = (NI)0; HEX3Atmp_552997_839829468 = (NI)0; LOC15 = (NI)0; LOC15 = len_291081_850551059(e0); HEX3Atmp_552997_839829468 = (LOC15 - 1); res_553000_839829468 = ((NI) 1); { while (1) { Tnode290802* it0; Tloc290816 tmp20; Tsym290834* field0; if (!(res_553000_839829468 <= HEX3Atmp_552997_839829468)) goto LA17; i_552944_839829468 = res_553000_839829468; it0 = (*e0).kindU.S6.sons->data[i_552944_839829468]; memset((void*)(&tmp20), 0, sizeof(tmp20)); tmp20.r = r0; field0 = lookupfieldagain_551154_839829468(p0, ty0, (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym, &tmp20.r); { if (!((*field0).loc.r == NIM_NIL)) goto LA20; internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_533)); } LA20: ; { NIM_BOOL LOC24; NI LOC25; LOC24 = (NIM_BOOL)0; LOC25 = (NI)0; LOC25 = len_291081_850551059(it0); LOC24 = (LOC25 == ((NI) 3)); if (!(LOC24)) goto LA26; LOC24 = (((*p0).options &(1U<<((NU)(((Toption168009) 2))&31U)))!=0); LA26: ; if (!LOC24) goto LA27; genfieldcheck_551504_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 2)], r0, field0, ty0); } LA27: ; add_177487_2381377266(&tmp20.r, ((NimStringDesc*) &T839829468_257)); add_177482_2381377266(&tmp20.r, (*field0).loc.r); tmp20.k = ((Tlockind290808) 1); tmp20.t = (*field0).loc.t; { if (!isref0) goto LA31; tmp20.s = ((Tstorageloc290812) 3); } goto LA29; LA31: ; { tmp20.s = ((Tstorageloc290812) 2); } LA29: ; expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&tmp20)); res_553000_839829468 += ((NI) 1); } LA17: ; } } { if (!((*d0).k == ((Tlockind290808) 0))) goto LA36; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI290816)); } goto LA34; LA36: ; { genassignment_537264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA34: ; }BeforeRet: ; } N_NIMCALL(void, gencast_554538_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Ttype290840* destt0; Ttype290840* srct0; destt0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832)); srct0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832)); { NIM_BOOL LOC3; Ropeobj177006* lbl0; Tloc290816 tmp0; TY177507 LOC7; TY533238 LOC8; TY177507 LOC9; Ropeobj177006* LOC10; LOC3 = (NIM_BOOL)0; LOC3 = ((IL64(1030792609808) &((NU64)1<<((NU)((*destt0).kind)&63U)))!=0); if (LOC3) goto LA4; LOC3 = ((IL64(1030792609808) &((NU64)1<<((NU)((*srct0).kind)&63U)))!=0); LA4: ; if (!LOC3) goto LA5; (*p0).labels += ((NI) 1); lbl0 = rope_177401_2381377266(((NI64) ((*p0).labels))); memset((void*)(&tmp0), 0, sizeof(tmp0)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = lbl0; tmp0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_536), LOC7, 1); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = gettypedesc_533673_839829468((*p0).module, srct0); LOC8[1] = gettypedesc_533673_839829468((*p0).module, destt0); LOC8[2] = lbl0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_537), LOC8, 3); tmp0.k = ((Tlockind290808) 6); tmp0.t = srct0; tmp0.s = ((Tstorageloc290812) 2); tmp0.flags = 0; expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = lbl0; LOC10 = (Ropeobj177006*)0; LOC10 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_538), LOC9, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC10, tmp0.s); } goto LA1; LA5: ; { gensomecast_554481_839829468(p0, e0, d0); } LA1: ; } N_NIMCALL(void, genconv_554633_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Ttype290840* desttype0; desttype0 = skiptypes_294099_850551059((*e0).typ, 8390656); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = comparetypes_324214_3876443242(desttype0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, ((Tdistinctcompare322427) 1), 0); if (!LOC3) goto LA4; expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0); } goto LA1; LA4: ; { gensomecast_554481_839829468(p0, e0, d0); } LA1: ; } static N_INLINE(NIM_BOOL, iscppref_550807_839829468)(Tcproc527021* p0, Ttype290840* typ0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; NIM_BOOL LOC3; Ttype290840* LOC6; Ttype290840* LOC8; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; LOC2 = LOC3; if (!(LOC2)) goto LA5; LOC6 = (Ttype290840*)0; LOC6 = skiptypes_294099_850551059(typ0, IL64(211106232576256)); LOC2 = ((*LOC6).kind == ((Ttypekind290244) 23)); LA5: ; LOC1 = LOC2; if (!(LOC1)) goto LA7; LOC8 = (Ttype290840*)0; LOC8 = skiptypes_294099_850551059(typ0, IL64(211106232576256)); LOC1 = !((((*LOC8).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0)); LA7: ; result0 = LOC1; return result0; } N_NIMCALL(void, genaddr_551051_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { { Ttype290840* LOC3; Tloc290816 a0; Ropeobj177006* LOC6; LOC3 = (Ttype290840*)0; LOC3 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); if (!((6291456 &((NU64)1<<((NU)((*LOC3).kind)&63U)))!=0)) goto LA4; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC6 = (Ropeobj177006*)0; LOC6 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_52), a0.r); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC6, a0.s); } goto LA1; LA4: ; { NIM_BOOL LOC8; Tctypekind527007 LOC9; LOC8 = (NIM_BOOL)0; LOC9 = (Tctypekind527007)0; LOC9 = maptype_531394_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); LOC8 = (LOC9 == ((Tctypekind527007) 17)); if (LOC8) goto LA10; LOC8 = iscppref_550807_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); LA10: ; if (!LOC8) goto LA11; expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); } goto LA1; LA11: ; { Tloc290816 a0; Ropeobj177006* LOC14; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC14 = (Ropeobj177006*)0; LOC14 = addrloc_536204_839829468((&a0)); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC14, a0.s); } LA1: ; } N_NIMCALL(void, genarrayelem_552093_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Ttype290840* ty0; Ttype290840* LOC1; Ropeobj177006* first0; NI64 LOC2; Ttype290840* LOC47; Ttype290840* LOC48; TY533238 LOC49; Ropeobj177006* LOC50; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, x0, (&a0)); initlocexpr_537283_839829468(p0, y0, (&b0)); LOC1 = (Ttype290840*)0; LOC1 = skiptypes_294099_850551059(a0.t, IL64(211106242013440)); ty0 = skiptypes_294099_850551059(LOC1, IL64(211106247256320)); LOC2 = (NI64)0; LOC2 = firstord_318001_3876443242(ty0); first0 = intliteral_537270_839829468(LOC2); { NIM_BOOL LOC5; LOC5 = (NIM_BOOL)0; LOC5 = (((*p0).options &(1U<<((NU)(((Toption168009) 4))&31U)))!=0); if (!(LOC5)) goto LA6; LOC5 = !((((*ty0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0)); LA6: ; if (!LOC5) goto LA7; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = isconstexpr_316510_2616423590(y0); if (!!(LOC11)) goto LA12; { NI64 LOC16; LOC16 = (NI64)0; LOC16 = firstord_318001_3876443242(ty0); if (!(LOC16 == IL64(0))) goto LA17; { NIM_BOOL LOC21; NI64 LOC22; NI64 LOC23; NI64 LOC25; NI64 LOC26; TY530811 LOC29; NI64 LOC30; LOC21 = (NIM_BOOL)0; LOC22 = (NI64)0; LOC22 = firstord_318001_3876443242(b0.t); LOC23 = (NI64)0; LOC23 = firstord_318001_3876443242(ty0); LOC21 = (LOC22 < LOC23); if (LOC21) goto LA24; LOC25 = (NI64)0; LOC25 = lastord_318004_3876443242(ty0); LOC26 = (NI64)0; LOC26 = lastord_318004_3876443242(b0.t); LOC21 = (LOC25 < LOC26); LA24: ; if (!LOC21) goto LA27; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdcharloc_536227_839829468((&b0)); LOC30 = (NI64)0; LOC30 = lastord_318004_3876443242(ty0); LOC29[1] = intliteral_537270_839829468(LOC30); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_539), LOC29, 2); } LA27: ; } goto LA14; LA17: ; { TY533238 LOC32; NI64 LOC33; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = rdcharloc_536227_839829468((&b0)); LOC32[1] = first0; LOC33 = (NI64)0; LOC33 = lastord_318004_3876443242(ty0); LOC32[2] = intliteral_537270_839829468(LOC33); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_540), LOC32, 3); } LA14: ; } goto LA9; LA12: ; { NI64 idx0; idx0 = getordvalue_318129_3876443242(y0); { NIM_BOOL LOC37; NI64 LOC38; NI64 LOC40; LOC37 = (NIM_BOOL)0; LOC38 = (NI64)0; LOC38 = firstord_318001_3876443242(ty0); LOC37 = (idx0 < LOC38); if (LOC37) goto LA39; LOC40 = (NI64)0; LOC40 = lastord_318004_3876443242(ty0); LOC37 = (LOC40 < idx0); LA39: ; if (!LOC37) goto LA41; localerror_194080_155036129((*x0).info, ((Tmsgkind189002) 86), ((NimStringDesc*) &T839829468_490)); } LA41: ; } LA9: ; } LA7: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA45; (*d0).s = a0.s; } LA45: ; LOC47 = (Ttype290840*)0; LOC47 = skiptypes_294099_850551059(ty0, IL64(211106240964864)); LOC48 = (Ttype290840*)0; LOC48 = elemtype_318394_3876443242(LOC47); memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_536188_839829468((&a0)); LOC49[1] = rdcharloc_536227_839829468((&b0)); LOC49[2] = first0; LOC50 = (Ropeobj177006*)0; LOC50 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_541), LOC49, 3); putintodest_548468_839829468(p0, d0, LOC48, LOC50, a0.s); } N_NIMCALL(void, genopenarrayelem_552169_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Ttype290840* LOC10; Ttype290840* LOC11; TY530811 LOC12; Ropeobj177006* LOC13; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, x0, (&a0)); initlocexpr_537283_839829468(p0, y0, (&b0)); { TY530811 LOC5; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 4))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&b0)); LOC5[1] = rdloc_536188_839829468((&a0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_542), LOC5, 2); } LA3: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA8; (*d0).s = a0.s; } LA8: ; LOC10 = (Ttype290840*)0; LOC10 = skiptypes_294099_850551059(a0.t, IL64(211106240964864)); LOC11 = (Ttype290840*)0; LOC11 = elemtype_318394_3876443242(LOC10); memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_536188_839829468((&a0)); LOC12[1] = rdcharloc_536227_839829468((&b0)); LOC13 = (Ropeobj177006*)0; LOC13 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC12, 2); putintodest_548468_839829468(p0, d0, LOC11, LOC13, a0.s); } N_NIMCALL(void, genseqelem_552205_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Ttype290840* ty0; Ttype290840* LOC27; Ttype290840* LOC28; TY530811 LOC29; Ropeobj177006* LOC30; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, x0, (&a0)); initlocexpr_537283_839829468(p0, y0, (&b0)); ty0 = skiptypes_294099_850551059(a0.t, IL64(211106242013440)); { Ttype290840* LOC5; if (!((6291456 &((NU64)1<<((NU)((*ty0).kind)&63U)))!=0)) goto LA3; LOC5 = (Ttype290840*)0; LOC5 = lastson_293377_850551059(ty0); ty0 = skiptypes_294099_850551059(LOC5, IL64(211106242013440)); } LA3: ; { if (!(((*p0).options &(1U<<((NU)(((Toption168009) 4))&31U)))!=0)) goto LA8; { TY533238 LOC14; if (!((*ty0).kind == ((Ttypekind290244) 28))) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_536188_839829468((&b0)); LOC14[1] = rdloc_536188_839829468((&a0)); LOC14[2] = lenfield_537305_839829468(p0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_543), LOC14, 3); } goto LA10; LA12: ; { TY533238 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_536188_839829468((&b0)); LOC16[1] = rdloc_536188_839829468((&a0)); LOC16[2] = lenfield_537305_839829468(p0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_544), LOC16, 3); } LA10: ; } LA8: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA19; (*d0).s = ((Tstorageloc290812) 3); } LA19: ; { Ttype290840* LOC23; TY177507 LOC26; LOC23 = (Ttype290840*)0; LOC23 = skiptypes_294099_850551059(a0.t, IL64(211106240964864)); if (!((6291456 &((NU64)1<<((NU)((*LOC23).kind)&63U)))!=0)) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = a0.r; a0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC26, 1); } LA24: ; LOC27 = (Ttype290840*)0; LOC27 = skiptypes_294099_850551059(a0.t, IL64(211106240964864)); LOC28 = (Ttype290840*)0; LOC28 = elemtype_318394_3876443242(LOC27); memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdloc_536188_839829468((&a0)); LOC29[1] = rdcharloc_536227_839829468((&b0)); LOC30 = (Ropeobj177006*)0; LOC30 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC29, 2); putintodest_548468_839829468(p0, d0, LOC28, LOC30, a0.s); } N_NIMCALL(void, gencstringelem_552144_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) { Tloc290816 a0; Tloc290816 b0; Ttype290840* ty0; Ttype290840* LOC5; Ttype290840* LOC6; TY530811 LOC7; Ropeobj177006* LOC8; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, x0, (&a0)); initlocexpr_537283_839829468(p0, y0, (&b0)); ty0 = skiptypes_294099_850551059(a0.t, IL64(211106242013440)); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA3; (*d0).s = a0.s; } LA3: ; LOC5 = (Ttype290840*)0; LOC5 = skiptypes_294099_850551059(ty0, IL64(211106240964864)); LOC6 = (Ttype290840*)0; LOC6 = elemtype_318394_3876443242(LOC5); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_536188_839829468((&a0)); LOC7[1] = rdcharloc_536227_839829468((&b0)); LOC8 = (Ropeobj177006*)0; LOC8 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC7, 2); putintodest_548468_839829468(p0, d0, LOC6, LOC8, a0.s); } N_NIMCALL(void, gentupleelem_551124_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; NI i0; Ropeobj177006* LOC5; Ttype290840* ty0; Ropeobj177006* r0; TY177507 LOC8; memset((void*)(&a0), 0, sizeof(a0)); i0 = (NI)0; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); { if (!((*d0).k == ((Tlockind290808) 0))) goto LA3; (*d0).s = a0.s; } LA3: ; LOC5 = (Ropeobj177006*)0; LOC5 = gettypedesc_533673_839829468((*p0).module, a0.t); ty0 = getuniquetype_526640_2036603609(a0.t); r0 = rdloc_536188_839829468((&a0)); switch ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind) { case ((Tnodekind290020) 6) ... ((Tnodekind290020) 15): { i0 = ((NI) ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval)); } break; default: { internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_545)); } break; } memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rope_177401_2381377266(((NI64) (i0))); addf_178205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC8, 1); putintodest_548468_839829468(p0, d0, (*ty0).sons->data[i0], r0, a0.s); } N_NIMCALL(void, genbracketexpr_552277_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Ttype290840* ty0; ty0 = skiptypes_294099_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440)); { Ttype290840* LOC5; if (!((6291456 &((NU64)1<<((NU)((*ty0).kind)&63U)))!=0)) goto LA3; LOC5 = (Ttype290840*)0; LOC5 = lastson_293377_850551059(ty0); ty0 = skiptypes_294099_850551059(LOC5, IL64(211106242013440)); } LA3: ; switch ((*ty0).kind) { case ((Ttypekind290244) 16): case ((Ttypekind290244) 4): { genarrayelem_552093_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind290244) 27): case ((Ttypekind290244) 48): { genopenarrayelem_552169_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind290244) 24): case ((Ttypekind290244) 28): { genseqelem_552205_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind290244) 29): { gencstringelem_552144_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind290244) 18): { gentupleelem_551124_839829468(p0, n0, d0); } break; default: { NimStringDesc* LOC12; LOC12 = (NimStringDesc*)0; LOC12 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI290244))->Sup.len + 21); appendString(LOC12, ((NimStringDesc*) &T839829468_547)); appendString(LOC12, reprEnum((NI)(*ty0).kind, (&NTI290244))); appendChar(LOC12, 41); internalerror_194100_155036129((*n0).info, LOC12); } break; } } N_NIMCALL(void, genderef_541921_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NIM_BOOL enforcederef0) { Tctypekind527007 mt0; { mt0 = maptype_531394_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((393216 &(1U<<((NU)(mt0)&31U)))!=0); if (!(LOC3)) goto LA4; LOC3 = !(enforcederef0); LA4: ; if (!LOC3) goto LA5; expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); { Ttype290840* LOC9; LOC9 = (Ttype290840*)0; LOC9 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); if (!((*LOC9).kind == ((Ttypekind290244) 22))) goto LA10; (*d0).s = ((Tstorageloc290812) 3); } LA10: ; } goto LA1; LA5: ; { Tloc290816 a0; Ttype290840* typ0; memset((void*)(&a0), 0, sizeof(a0)); typ0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { NIM_BOOL LOC15; NIM_BOOL LOC16; NIM_BOOL LOC17; NIM_BOOL LOC20; Tnode290802* LOC25; Tnode290802* LOC26; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC17 = (NIM_BOOL)0; LOC17 = ((*typ0).kind == ((Ttypekind290244) 23)); if (!(LOC17)) goto LA18; LOC17 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0)); LA18: ; LOC16 = LOC17; if (!(LOC16)) goto LA19; LOC20 = (NIM_BOOL)0; LOC20 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC20) goto LA21; LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA21: ; LOC16 = LOC20; LA19: ; LOC15 = LOC16; if (!(LOC15)) goto LA22; LOC15 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 64)); LA22: ; if (!LOC15) goto LA23; LOC25 = (Tnode290802*)0; LOC25 = HEX5BHEX5D_291238_850551059(e0, ((NI) 0)); LOC26 = (Tnode290802*)0; LOC26 = HEX5BHEX5D_291238_850551059(LOC25, ((NI) 0)); initlocexprsingleuse_537289_839829468(p0, LOC26, d0); goto BeforeRet; } goto LA13; LA23: ; { initlocexprsingleuse_537289_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA13: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA30; switch ((*typ0).kind) { case ((Ttypekind290244) 22): { (*d0).s = ((Tstorageloc290812) 3); } break; case ((Ttypekind290244) 23): { (*d0).s = ((Tstorageloc290812) 0); { NIM_BOOL LOC36; NIM_BOOL LOC37; NIM_BOOL LOC39; Ropeobj177006* LOC44; LOC36 = (NIM_BOOL)0; LOC37 = (NIM_BOOL)0; LOC37 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0)); if (!(LOC37)) goto LA38; LOC39 = (NIM_BOOL)0; LOC39 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC39) goto LA40; LOC39 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA40: ; LOC37 = LOC39; LA38: ; LOC36 = LOC37; if (!(LOC36)) goto LA41; LOC36 = ((*e0).kind == ((Tnodekind290020) 65)); LA41: ; if (!LOC36) goto LA42; LOC44 = (Ropeobj177006*)0; LOC44 = rdloc_536188_839829468((&a0)); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC44, a0.s); goto BeforeRet; } LA42: ; } break; case ((Ttypekind290244) 21): { (*d0).s = ((Tstorageloc290812) 0); } break; default: { NimStringDesc* LOC47; LOC47 = (NimStringDesc*)0; LOC47 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI290244))->Sup.len + 9); appendString(LOC47, ((NimStringDesc*) &T839829468_548)); appendString(LOC47, reprEnum((NI)(*typ0).kind, (&NTI290244))); internalerror_194100_155036129((*e0).info, LOC47); } break; } } goto LA28; LA30: ; { NIM_BOOL LOC49; LOC49 = (NIM_BOOL)0; LOC49 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC49) goto LA50; LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA50: ; if (!LOC49) goto LA51; { NIM_BOOL LOC55; NIM_BOOL LOC56; Ropeobj177006* LOC61; LOC55 = (NIM_BOOL)0; LOC56 = (NIM_BOOL)0; LOC56 = ((*typ0).kind == ((Ttypekind290244) 23)); if (!(LOC56)) goto LA57; LOC56 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0)); LA57: ; LOC55 = LOC56; if (!(LOC55)) goto LA58; LOC55 = ((*e0).kind == ((Tnodekind290020) 65)); LA58: ; if (!LOC55) goto LA59; LOC61 = (Ropeobj177006*)0; LOC61 = rdloc_536188_839829468((&a0)); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC61, a0.s); goto BeforeRet; } LA59: ; } goto LA28; LA51: ; LA28: ; { NIM_BOOL LOC64; Ropeobj177006* LOC68; LOC64 = (NIM_BOOL)0; LOC64 = enforcederef0; if (!(LOC64)) goto LA65; LOC64 = (mt0 == ((Tctypekind527007) 18)); LA65: ; if (!LOC64) goto LA66; LOC68 = (Ropeobj177006*)0; LOC68 = rdloc_536188_839829468((&a0)); putintodest_548468_839829468(p0, d0, (*a0.t).sons->data[((NI) 0)], LOC68, a0.s); } goto LA62; LA66: ; { TY177507 LOC70; Ropeobj177006* LOC71; memset((void*)LOC70, 0, sizeof(LOC70)); LOC70[0] = rdloc_536188_839829468((&a0)); LOC71 = (Ropeobj177006*)0; LOC71 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC70, 1); putintodest_548468_839829468(p0, d0, (*e0).typ, LOC71, a0.s); } LA62: ; } LA1: ; }BeforeRet: ; } N_NIMCALL(Ttype290840*, genrecordfieldaux_551096_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tloc290816* a0) { Ttype290840* result0; Ropeobj177006* LOC9; result0 = (Ttype290840*)0; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], a0); { if (!!(((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind290020) 3)))) goto LA3; internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_549)); } LA3: ; { if (!((*d0).k == ((Tlockind290808) 0))) goto LA7; (*d0).s = (*a0).s; } LA7: ; LOC9 = (Ropeobj177006*)0; LOC9 = gettypedesc_533673_839829468((*p0).module, (*a0).t); result0 = getuniquetype_526640_2036603609((*a0).t); return result0; } N_NIMCALL(void, genrecordfield_551448_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* ty0; Ropeobj177006* r0; Tsym290834* f0; memset((void*)(&a0), 0, sizeof(a0)); ty0 = genrecordfieldaux_551096_839829468(p0, e0, d0, (&a0)); r0 = rdloc_536188_839829468((&a0)); f0 = (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; { TY177507 LOC5; if (!((*ty0).kind == ((Ttypekind290244) 18))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_177401_2381377266(((NI64) ((*f0).position))); addf_178205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC5, 1); putintodest_548468_839829468(p0, d0, (*f0).typ, r0, a0.s); } goto LA1; LA3: ; { Tsym290834* field0; TY177507 LOC11; field0 = lookupfieldagain_551154_839829468(p0, ty0, f0, &r0); { if (!((*field0).loc.r == NIM_NIL)) goto LA9; internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_550)); } LA9: ; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = (*field0).loc.r; addf_178205_2381377266(&r0, ((NimStringDesc*) &T839829468_551), LOC11, 1); putintodest_548468_839829468(p0, d0, (*field0).typ, r0, a0.s); } LA1: ; } N_NIMCALL(void, gencheckedrecordfield_552046_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) { { Tloc290816 a0; Ttype290840* ty0; Ropeobj177006* r0; Tsym290834* f0; Tsym290834* field0; TY177507 LOC9; Ropeobj177006* LOC10; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 2))&31U)))!=0)) goto LA3; memset((void*)(&a0), 0, sizeof(a0)); ty0 = genrecordfieldaux_551096_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0, (&a0)); r0 = rdloc_536188_839829468((&a0)); f0 = (*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; field0 = lookupfieldagain_551154_839829468(p0, ty0, f0, &r0); { if (!((*field0).loc.r == NIM_NIL)) goto LA7; internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_532)); } LA7: ; genfieldcheck_551504_839829468(p0, e0, r0, field0, ty0); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = (*field0).loc.r; LOC10 = (Ropeobj177006*)0; LOC10 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_551), LOC9, 1); add_177482_2381377266(&r0, LOC10); putintodest_548468_839829468(p0, d0, (*field0).typ, r0, a0.s); } goto LA1; LA3: ; { genrecordfield_551448_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); } LA1: ; } N_NIMCALL(NI, startblock_541978_839829468)(Tcproc527021* p0, NimStringDesc* start0, Ropeobj177006** args0, NI args0Len0) { NI result0; result0 = (NI)0; linecg_530707_839829468(p0, ((Tcprocsection527011) 2), start0, args0, args0Len0); (*p0).labels += ((NI) 1); result0 = ((*p0).blocks ? (*p0).blocks->Sup.len : 0); (*p0).blocks = (TY527095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock527019), ((NI) ((NI)(result0 + ((NI) 1))))); (*p0).blocks->data[result0].id = ((NI) ((*p0).labels)); (*p0).blocks->data[result0].nestedtrystmts = ((NI16) (((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0))); (*p0).blocks->data[result0].nestedexceptstmts = ((NI16) ((*p0).inexceptblock)); return result0; } N_NIMCALL(Ropeobj177006*, blockbody_542025_839829468)(Tblock527019* b0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = (*b0).sections[(((Tcprocsection527011) 0))- 0]; { TY177507 LOC5; if (!(((NI16) 0) < (*b0).framelen)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_177401_2381377266(((NI64) ((*b0).framelen))); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_554), LOC5, 1); } LA3: ; add_177482_2381377266(&result0, (*b0).sections[(((Tcprocsection527011) 1))- 0]); add_177482_2381377266(&result0, (*b0).sections[(((Tcprocsection527011) 2))- 0]); return result0; } N_NIMCALL(void, endblock_542035_839829468)(Tcproc527021* p0, Ropeobj177006* blockend0) { NI topblock0; Ropeobj177006* LOC1; topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); LOC1 = (Ropeobj177006*)0; LOC1 = blockbody_542025_839829468((&(*p0).blocks->data[topblock0])); add_177482_2381377266(&(*p0).blocks->data[(NI)(topblock0 - ((NI) 1))].sections[(((Tcprocsection527011) 2))- 0], LOC1); (*p0).blocks = (TY527095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock527019), ((NI) (topblock0))); line_530690_839829468(p0, ((Tcprocsection527011) 2), blockend0); } N_NIMCALL(void, endblock_542060_839829468)(Tcproc527021* p0) { NI topblock0; Ropeobj177006* blockend0; NI16 framelen0; topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); { TY177507 LOC5; if (!!(((*p0).blocks->data[topblock0].label == NIM_NIL))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = (*p0).blocks->data[topblock0].label; blockend0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_552), LOC5, 1); } goto LA1; LA3: ; { TY531289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); blockend0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_160), LOC7, 0); } LA1: ; framelen0 = (*p0).blocks->data[topblock0].framelen; { TY177507 LOC12; if (!(((NI16) 0) < framelen0)) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_177401_2381377266(((NI64) (framelen0))); addf_178205_2381377266(&blockend0, ((NimStringDesc*) &T839829468_553), LOC12, 1); } LA10: ; endblock_542035_839829468(p0, blockend0); } N_NIMCALL(void, genblock_544083_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { NI oldbreakidx_544099_839829468; TY531289 LOC8; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_295441_850551059((*n0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind290808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA6: ; oldbreakidx_544099_839829468 = (*p0).breakidx; memset((void*)LOC8, 0, sizeof(LOC8)); (*p0).breakidx = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC8, 0); { Tsym290834* sym0; if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA11; sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; (*sym0).loc.k = ((Tlockind290808) 10); (*sym0).position = (NI)((*p0).breakidx + ((NI) 1)); } LA11: ; expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], d0); endblock_542060_839829468(p0); (*p0).breakidx = oldbreakidx_544099_839829468; } N_NIMCALL(void, genstmtlistexpr_556402_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { NI length0; length0 = sonslen_293351_850551059(n0); { NI i_556420_839829468; NI HEX3Atmp_556424_839829468; NI res_556427_839829468; i_556420_839829468 = (NI)0; HEX3Atmp_556424_839829468 = (NI)0; HEX3Atmp_556424_839829468 = (NI)(length0 - ((NI) 2)); res_556427_839829468 = ((NI) 0); { while (1) { if (!(res_556427_839829468 <= HEX3Atmp_556424_839829468)) goto LA3; i_556420_839829468 = res_556427_839829468; genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[i_556420_839829468]); res_556427_839829468 += ((NI) 1); } LA3: ; } } { if (!(((NI) 0) < length0)) goto LA6; expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0); } LA6: ; } N_NIMCALL(void, genif_542982_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Tloc290816 a0; Ropeobj177006* lelse0; Ropeobj177006* lend0; memset((void*)(&a0), 0, sizeof(a0)); lelse0 = (Ropeobj177006*)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_295441_850551059((*n0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind290808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA6: ; genlinedir_530823_839829468(p0, n0); lend0 = getlabel_537217_839829468(p0); { NI i_543011_839829468; NI HEX3Atmp_543435_839829468; NI LOC9; NI res_543438_839829468; i_543011_839829468 = (NI)0; HEX3Atmp_543435_839829468 = (NI)0; LOC9 = (NI)0; LOC9 = sonslen_293351_850551059(n0); HEX3Atmp_543435_839829468 = (NI)(LOC9 - ((NI) 1)); res_543438_839829468 = ((NI) 0); { while (1) { Tnode290802* it0; if (!(res_543438_839829468 <= HEX3Atmp_543435_839829468)) goto LA11; i_543011_839829468 = res_543438_839829468; { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = ((*d0).k == ((Tlockind290808) 1)); if (!(LOC14)) goto LA15; LOC14 = isemptytype_295441_850551059((*n0).typ); LA15: ; if (!LOC14) goto LA16; (*d0).k = ((Tlockind290808) 0); } LA16: ; it0 = (*n0).kindU.S6.sons->data[i_543011_839829468]; { NI LOC20; TY531289 LOC23; NI LOC24; TY530811 LOC25; LOC20 = (NI)0; LOC20 = len_291081_850551059(it0); if (!(LOC20 == ((NI) 2))) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); LOC24 = (NI)0; LOC24 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC23, 0); initlocexprsingleuse_537289_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], (&a0)); lelse0 = getlabel_537217_839829468(p0); (*p0).labels += ((NI) 1); memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = rdloc_536188_839829468((&a0)); LOC25[1] = lelse0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_555), LOC25, 2); { NIM_BOOL LOC28; Ropeobj177006** LOC32; Ropeobj177006** LOC33; LOC28 = (NIM_BOOL)0; LOC28 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC28) goto LA29; LOC28 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA29: ; if (!LOC28) goto LA30; LOC32 = (Ropeobj177006**)0; LOC32 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177487_2381377266(LOC32, ((NimStringDesc*) &T839829468_223)); expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0); LOC33 = (Ropeobj177006**)0; LOC33 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177487_2381377266(LOC33, ((NimStringDesc*) &T839829468_280)); } goto LA26; LA30: ; { expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0); } LA26: ; endblock_542060_839829468(p0); { NI LOC37; TY177507 LOC40; LOC37 = (NI)0; LOC37 = sonslen_293351_850551059(n0); if (!(((NI) 1) < LOC37)) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = lend0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_556), LOC40, 1); } LA38: ; fixlabel_537230_839829468(p0, lelse0); } goto LA18; LA21: ; { NI LOC42; TY531289 LOC45; NI LOC46; LOC42 = (NI)0; LOC42 = len_291081_850551059(it0); if (!(LOC42 == ((NI) 1))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (NI)0; LOC46 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0); expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], d0); endblock_542060_839829468(p0); } goto LA18; LA43: ; { internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_557)); } LA18: ; res_543438_839829468 += ((NI) 1); } LA11: ; } } { NI LOC50; LOC50 = (NI)0; LOC50 = sonslen_293351_850551059(n0); if (!(((NI) 1) < LOC50)) goto LA51; fixlabel_537230_839829468(p0, lend0); } LA51: ; } N_NIMCALL(void, downconv_556581_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], d0); } goto LA1; LA5: ; { Ttype290840* dest0; Tnode290802* arg0; Ttype290840* src0; Tloc290816 a0; Ropeobj177006* r0; NIM_BOOL isref0; Ttype290840* LOC10; dest0 = skiptypes_294099_850551059((*n0).typ, IL64(211106247256320)); arg0 = (*n0).kindU.S6.sons->data[((NI) 0)]; { while (1) { if (!((*arg0).kind == ((Tnodekind290020) 66))) goto LA9; arg0 = (*arg0).kindU.S6.sons->data[((NI) 0)]; } LA9: ; } src0 = skiptypes_294099_850551059((*arg0).typ, IL64(211106247256320)); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, arg0, (&a0)); r0 = rdloc_536188_839829468((&a0)); LOC10 = (Ttype290840*)0; LOC10 = skiptypes_294099_850551059((*arg0).typ, IL64(211106232576256)); isref0 = ((14680064 &((NU64)1<<((NU)((*LOC10).kind)&63U)))!=0); { if (!isref0) goto LA13; add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_558)); } goto LA11; LA13: ; { add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); } LA11: ; { NI i_556650_839829468; NI HEX3Atmp_556677_839829468; NI LOC17; NI res_556680_839829468; i_556650_839829468 = (NI)0; HEX3Atmp_556677_839829468 = (NI)0; LOC17 = (NI)0; LOC17 = inheritancediff_324252_3876443242(dest0, src0); HEX3Atmp_556677_839829468 = (LOC17 > 0? (LOC17) : -(LOC17)); res_556680_839829468 = ((NI) 2); { while (1) { if (!(res_556680_839829468 <= HEX3Atmp_556677_839829468)) goto LA19; i_556650_839829468 = res_556680_839829468; add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); res_556680_839829468 += ((NI) 1); } LA19: ; } } { if (!isref0) goto LA22; { NIM_BOOL LOC26; Ttype290840* LOC28; TY530811 LOC31; LOC26 = (NIM_BOOL)0; LOC26 = ((*d0).k == ((Tlockind290808) 0)); if (!(LOC26)) goto LA27; LOC28 = (Ttype290840*)0; LOC28 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256)); LOC26 = ((14680064 &((NU64)1<<((NU)((*LOC28).kind)&63U)))!=0); LA27: ; if (!LOC26) goto LA29; gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = rdloc_536188_839829468((&(*d0))); LOC31[1] = r0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_559), LOC31, 2); } goto LA24; LA29: ; { r0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_52), r0); putintodest_548468_839829468(p0, d0, (*n0).typ, r0, a0.s); } LA24: ; } goto LA20; LA22: ; { putintodest_548468_839829468(p0, d0, (*n0).typ, r0, a0.s); } LA20: ; } LA1: ; } N_NIMCALL(void, upconv_556431_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* dest0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); dest0 = skiptypes_294099_850551059((*n0).typ, IL64(211106247256320)); { NIM_BOOL LOC3; NIM_BOOL LOC5; Ropeobj177006* r0; Ropeobj177006* nilcheck0; Ttype290840* t0; LOC3 = (NIM_BOOL)0; LOC3 = (((*p0).options &(1U<<((NU)(((Toption168009) 1))&31U)))!=0); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = isobjlackingtypefield_531515_839829468(dest0); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; r0 = rdloc_536188_839829468((&a0)); nilcheck0 = NIM_NIL; t0 = skiptypes_294099_850551059(a0.t, IL64(211106232576256)); { while (1) { Ttype290840* LOC23; if (!((14680064 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)) goto LA9; { if (!!(((*t0).kind == ((Ttypekind290244) 23)))) goto LA12; nilcheck0 = r0; } LA12: ; { NIM_BOOL LOC16; NIM_BOOL LOC18; TY177507 LOC22; LOC16 = (NIM_BOOL)0; LOC16 = !(((*t0).kind == ((Ttypekind290244) 23))); if (LOC16) goto LA17; LOC18 = (NIM_BOOL)0; LOC18 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC18) goto LA19; LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA19: ; LOC16 = !(LOC18); LA17: ; if (!LOC16) goto LA20; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = r0; r0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC22, 1); } LA20: ; LOC23 = (Ttype290840*)0; LOC23 = lastson_293377_850551059(t0); t0 = skiptypes_294099_850551059(LOC23, IL64(211106232576256)); } LA9: ; } { NIM_BOOL LOC26; LOC26 = (NIM_BOOL)0; LOC26 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC26) goto LA27; LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA27: ; if (!!(LOC26)) goto LA28; { while (1) { NIM_BOOL LOC32; LOC32 = (NIM_BOOL)0; LOC32 = ((*t0).kind == ((Ttypekind290244) 17)); if (!(LOC32)) goto LA33; LOC32 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); LA33: ; if (!LOC32) goto LA31; add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); t0 = skiptypes_294099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360)); } LA31: ; } } LA28: ; { TY533238 LOC38; if (!!((nilcheck0 == NIM_NIL))) goto LA36; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = nilcheck0; LOC38[1] = r0; LOC38[2] = gentypeinfo_533941_839829468((*p0).module, dest0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_560), LOC38, 3); } goto LA34; LA36: ; { TY530811 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = r0; LOC40[1] = gentypeinfo_533941_839829468((*p0).module, dest0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_561), LOC40, 2); } LA34: ; } LA6: ; { TY530811 LOC45; Ropeobj177006* LOC46; if (!!(((*(*(*n0).kindU.S6.sons->data[((NI) 0)]).typ).kind == ((Ttypekind290244) 17)))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = gettypedesc_533673_839829468((*p0).module, (*n0).typ); LOC45[1] = rdloc_536188_839829468((&a0)); LOC46 = (Ropeobj177006*)0; LOC46 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC45, 2); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC46, a0.s); } goto LA41; LA43: ; { TY530811 LOC48; Ropeobj177006* LOC49; memset((void*)LOC48, 0, sizeof(LOC48)); LOC48[0] = gettypedesc_533673_839829468((*p0).module, dest0); LOC48[1] = addrloc_536204_839829468((&a0)); LOC49 = (Ropeobj177006*)0; LOC49 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_429), LOC48, 2); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC49, a0.s); } LA41: ; } N_NIMCALL(void, genrangechck_554591_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* magic0) { Tloc290816 a0; Ttype290840* dest0; memset((void*)(&a0), 0, sizeof(a0)); dest0 = skiptypes_294099_850551059((*n0).typ, IL64(211106240964864)); { NIM_BOOL LOC3; Ttype290840* LOC5; TY530811 LOC8; Ropeobj177006* LOC9; LOC3 = (NIM_BOOL)0; LOC3 = !((((*p0).options &(1U<<((NU)(((Toption168009) 3))&31U)))!=0)); if (LOC3) goto LA4; LOC5 = (Ttype290840*)0; LOC5 = skiptypes_294099_850551059(dest0, 1048576); LOC3 = ((IL64(34084860461056) &((NU64)1<<((NU)((*LOC5).kind)&63U)))!=0); LA4: ; if (!LOC3) goto LA6; initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = gettypedesc_533673_839829468((*p0).module, dest0); LOC8[1] = rdcharloc_536227_839829468((&a0)); LOC9 = (Ropeobj177006*)0; LOC9 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC8, 2); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC9, a0.s); } goto LA1; LA6: ; { TY534475 LOC11; Ropeobj177006* LOC12; initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_533673_839829468((*p0).module, dest0); LOC11[1] = rdcharloc_536227_839829468((&a0)); LOC11[2] = genliteral_547476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], dest0); LOC11[3] = genliteral_547476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 2)], dest0); LOC11[4] = rope_177277_2381377266(magic0); LOC12 = (Ropeobj177006*)0; LOC12 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_562), LOC11, 5); putintodest_548468_839829468(p0, d0, dest0, LOC12, a0.s); } LA1: ; } N_NIMCALL(void, convstrtocstr_554643_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* LOC1; TY177507 LOC2; Ropeobj177006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (Ttype290840*)0; LOC1 = skiptypes_294099_850551059((*n0).typ, IL64(211106240964864)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_536188_839829468((&a0)); LOC3 = (Ropeobj177006*)0; LOC3 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_485), LOC2, 1); putintodest_548468_839829468(p0, d0, LOC1, LOC3, a0.s); } N_NIMCALL(void, convcstrtostr_554655_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { Tloc290816 a0; Ttype290840* LOC1; TY177507 LOC2; Ropeobj177006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (Ttype290840*)0; LOC1 = skiptypes_294099_850551059((*n0).typ, IL64(211106240964864)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_536188_839829468((&a0)); LOC3 = (Ropeobj177006*)0; LOC3 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_411), LOC2, 1); putintodest_548468_839829468(p0, d0, LOC1, LOC3, a0.s); gcusage_552439_839829468(n0); } static N_INLINE(NIM_BOOL, isroutine_295324_850551059)(Tsym290834* s0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((258048 &(1U<<((NU)((*s0).kind)&31U)))!=0); return result0; } static N_INLINE(NIM_BOOL, isconstclosure_555810_839829468)(Tnode290802* n0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC2)) goto LA3; LOC2 = isroutine_295324_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA4; LOC1 = ((*(*n0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind290020) 23)); LA4: ; result0 = LOC1; return result0; } N_NIMCALL(void, genclosure_555836_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { { NIM_BOOL LOC3; Ropeobj177006* tmp0; Ropeobj177006* LOC6; TY533238 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = isconstclosure_555810_839829468(n0); if (!LOC3) goto LA4; (*(*p0).module).labels += ((NI) 1); LOC6 = (Ropeobj177006*)0; LOC6 = rope_177401_2381377266(((NI64) ((*(*p0).module).labels))); tmp0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_566), LOC6); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_533673_839829468((*p0).module, (*n0).typ); LOC7[1] = tmp0; LOC7[2] = genconstexpr_552849_839829468(p0, n0); addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC7, 3); putintodest_548468_839829468(p0, d0, (*n0).typ, tmp0, ((Tstorageloc290812) 1)); } goto LA1; LA4: ; { Tloc290816 tmp0; Tloc290816 a0; Tloc290816 b0; TY533238 LOC14; memset((void*)(&tmp0), 0, sizeof(tmp0)); memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&b0)); { Tnode290802* LOC11; LOC11 = (Tnode290802*)0; LOC11 = skipconv_326882_3876443242((*n0).kindU.S6.sons->data[((NI) 0)]); if (!((*LOC11).kind == ((Tnodekind290020) 155))) goto LA12; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_567)); } LA12: ; gettemp_535032_839829468(p0, (*n0).typ, (&tmp0), NIM_FALSE); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_536188_839829468((&tmp0)); LOC14[1] = rdloc_536188_839829468((&a0)); LOC14[2] = rdloc_536188_839829468((&b0)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_568), LOC14, 3); putlocintodest_537258_839829468(p0, d0, (&tmp0)); } LA1: ; } static N_INLINE(Ropeobj177006*, assignlabel_542020_839829468)(Tblock527019* b0) { Ropeobj177006* result0; Ropeobj177006* LOC1; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = rope_177401_2381377266(((NI64) ((*b0).id))); unsureAsgnRef((void**) (&(*b0).label), HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC1)); result0 = (*b0).label; return result0; } N_NIMCALL(void, gencomputedgoto_543744_839829468)(Tcproc527021* p0, Tnode290802* n0) { NI casepos0; NI arraysize0; NI id0; Ropeobj177006* tmp0; TY177507 LOC27; Ropeobj177006* gotoarray0; TY530811 LOC28; TY177507 LOC33; NI topblock0; Ropeobj177006* oldbody0; Ropeobj177006* tailb0; Ropeobj177006* taila0; Tnode290802* casestmt0; Tloc290816 a_543871_839829468; TY530811 LOC41; { casepos0 = ((NI) -1); arraysize0 = (NI)0; { NI i_543768_839829468; NI HEX3Atmp_543934_839829468; NI LOC2; NI res_543937_839829468; i_543768_839829468 = (NI)0; HEX3Atmp_543934_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_291081_850551059(n0); HEX3Atmp_543934_839829468 = (LOC2 - 1); res_543937_839829468 = ((NI) 0); { while (1) { Tnode290802* it0; if (!(res_543937_839829468 <= HEX3Atmp_543934_839829468)) goto LA4; i_543768_839829468 = res_543937_839829468; it0 = (*n0).kindU.S6.sons->data[i_543768_839829468]; { NI64 asize0; if (!((*it0).kind == ((Tnodekind290020) 97))) goto LA7; { Tnode290802* LOC11; LOC11 = (Tnode290802*)0; LOC11 = lastson_293364_850551059(it0); if (!!(((*LOC11).kind == ((Tnodekind290020) 85)))) goto LA12; localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_570)); goto BeforeRet; } LA12: ; casepos0 = i_543768_839829468; asize0 = lengthord_318007_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ); { if (!(IL64(10000) < asize0)) goto LA16; localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_571)); goto BeforeRet; } LA16: ; arraysize0 = ((NI) (asize0)); { NI64 LOC20; LOC20 = (NI64)0; LOC20 = firstord_318001_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ); if (!!((LOC20 == IL64(0)))) goto LA21; localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_572)); goto BeforeRet; } LA21: ; } LA7: ; res_543937_839829468 += ((NI) 1); } LA4: ; } } { if (!(casepos0 < ((NI) 0))) goto LA25; localerror_194085_155036129((*n0).info, ((NimStringDesc*) &T839829468_573)); goto BeforeRet; } LA25: ; id0 = (NI)(((NI) ((*p0).labels)) + ((NI) 1)); (*p0).labels += (NI)(arraysize0 + ((NI) 1)); memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = rope_177401_2381377266(((NI64) (id0))); tmp0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_574), LOC27, 1); memset((void*)LOC28, 0, sizeof(LOC28)); LOC28[0] = tmp0; LOC28[1] = rope_177401_2381377266(((NI64) (arraysize0))); gotoarray0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_575), LOC28, 2); { NI i_543819_839829468; NI HEX3Atmp_543942_839829468; NI res_543945_839829468; i_543819_839829468 = (NI)0; HEX3Atmp_543942_839829468 = (NI)0; HEX3Atmp_543942_839829468 = (NI)(arraysize0 - ((NI) 1)); res_543945_839829468 = ((NI) 1); { while (1) { TY177507 LOC32; if (!(res_543945_839829468 <= HEX3Atmp_543942_839829468)) goto LA31; i_543819_839829468 = res_543945_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = rope_177401_2381377266(((NI64) ((NI)(((NI) (id0)) + i_543819_839829468)))); addf_178205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_576), LOC32, 1); res_543945_839829468 += ((NI) 1); } LA31: ; } } memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rope_177401_2381377266(((NI64) ((NI)(((NI) (id0)) + arraysize0)))); addf_178205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_577), LOC33, 1); line_530690_839829468(p0, ((Tcprocsection527011) 0), gotoarray0); topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); oldbody0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]), NIM_NIL); { NI j_543854_839829468; NI HEX3Atmp_543950_839829468; NI HEX3Atmp_543951_839829468; NI LOC35; NI res_543954_839829468; j_543854_839829468 = (NI)0; HEX3Atmp_543950_839829468 = (NI)0; HEX3Atmp_543951_839829468 = (NI)0; HEX3Atmp_543950_839829468 = (NI)(casepos0 + ((NI) 1)); LOC35 = (NI)0; LOC35 = len_291081_850551059(n0); HEX3Atmp_543951_839829468 = (LOC35 - 1); res_543954_839829468 = HEX3Atmp_543950_839829468; { while (1) { if (!(res_543954_839829468 <= HEX3Atmp_543951_839829468)) goto LA37; j_543854_839829468 = res_543954_839829468; genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[j_543854_839829468]); res_543954_839829468 += ((NI) 1); } LA37: ; } } tailb0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]), NIM_NIL); { NI j_543866_839829468; NI HEX3Atmp_543959_839829468; NI res_543962_839829468; j_543866_839829468 = (NI)0; HEX3Atmp_543959_839829468 = (NI)0; HEX3Atmp_543959_839829468 = (NI)(casepos0 - ((NI) 1)); res_543962_839829468 = ((NI) 0); { while (1) { if (!(res_543962_839829468 <= HEX3Atmp_543959_839829468)) goto LA40; j_543866_839829468 = res_543962_839829468; genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[j_543866_839829468]); res_543962_839829468 += ((NI) 1); } LA40: ; } } taila0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]), HEX26_177418_2381377266(oldbody0, taila0)); casestmt0 = (*n0).kindU.S6.sons->data[casepos0]; memset((void*)(&a_543871_839829468), 0, sizeof(a_543871_839829468)); initlocexpr_537283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a_543871_839829468)); memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = tmp0; LOC41[1] = rdloc_536188_839829468((&a_543871_839829468)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_578), LOC41, 2); { NI i_543894_839829468; NI HEX3Atmp_543978_839829468; NI LOC43; NI res_543981_839829468; i_543894_839829468 = (NI)0; HEX3Atmp_543978_839829468 = (NI)0; LOC43 = (NI)0; LOC43 = len_291081_850551059(casestmt0); HEX3Atmp_543978_839829468 = (LOC43 - 1); res_543981_839829468 = ((NI) 1); { while (1) { TY531289 LOC46; NI LOC47; Tnode290802* it0; Tnode290802* LOC57; Ropeobj177006** LOC58; Ropeobj177006** LOC59; Tloc290816 a0; TY530811 LOC60; if (!(res_543981_839829468 <= HEX3Atmp_543978_839829468)) goto LA45; i_543894_839829468 = res_543981_839829468; memset((void*)LOC46, 0, sizeof(LOC46)); LOC47 = (NI)0; LOC47 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC46, 0); it0 = (*casestmt0).kindU.S6.sons->data[i_543894_839829468]; { NI j_543910_839829468; NI HEX3Atmp_543970_839829468; NI LOC49; NI res_543973_839829468; j_543910_839829468 = (NI)0; HEX3Atmp_543970_839829468 = (NI)0; LOC49 = (NI)0; LOC49 = len_291081_850551059(it0); HEX3Atmp_543970_839829468 = (NI)(LOC49 - ((NI) 2)); res_543973_839829468 = ((NI) 0); { while (1) { NI64 val0; TY177507 LOC56; if (!(res_543973_839829468 <= HEX3Atmp_543970_839829468)) goto LA51; j_543910_839829468 = res_543973_839829468; { if (!((*(*it0).kindU.S6.sons->data[j_543910_839829468]).kind == ((Tnodekind290020) 44))) goto LA54; localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579)); goto BeforeRet; } LA54: ; val0 = getordvalue_318129_3876443242((*it0).kindU.S6.sons->data[j_543910_839829468]); memset((void*)LOC56, 0, sizeof(LOC56)); LOC56[0] = intliteral_537270_839829468((NI64)((NI64)(val0 + ((NI64) (id0))) + IL64(1))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_580), LOC56, 1); res_543973_839829468 += ((NI) 1); } LA51: ; } } LOC57 = (Tnode290802*)0; LOC57 = lastson_293364_850551059(it0); genstmts_537244_839829468(p0, LOC57); LOC58 = (Ropeobj177006**)0; LOC58 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(LOC58, tailb0); LOC59 = (Ropeobj177006**)0; LOC59 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); add_177482_2381377266(LOC59, taila0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC60, 0, sizeof(LOC60)); LOC60[0] = tmp0; LOC60[1] = rdloc_536188_839829468((&a0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_578), LOC60, 2); endblock_542060_839829468(p0); res_543981_839829468 += ((NI) 1); } LA45: ; } } }BeforeRet: ; } N_NIMCALL(void, genwhilestmt_543985_839829468)(Tcproc527021* p0, Tnode290802* t0) { Tloc290816 a0; NI oldbreakidx_544011_839829468; TY531289 LOC1; Tnode290802* loopbody0; memset((void*)(&a0), 0, sizeof(a0)); (*p0).withinloop += ((NI) 1); genlinedir_530823_839829468(p0, t0); oldbreakidx_544011_839829468 = (*p0).breakidx; memset((void*)LOC1, 0, sizeof(LOC1)); (*p0).breakidx = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_569), LOC1, 0); (*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE; initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); { NIM_BOOL LOC4; Ropeobj177006* label0; TY530811 LOC8; LOC4 = (NIM_BOOL)0; LOC4 = !(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 6))); if (LOC4) goto LA5; LOC4 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval == IL64(0)); LA5: ; if (!LOC4) goto LA6; label0 = assignlabel_542020_839829468((&(*p0).blocks->data[(*p0).breakidx])); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_536188_839829468((&a0)); LOC8[1] = label0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_555), LOC8, 2); } LA6: ; loopbody0 = (*t0).kindU.S6.sons->data[((NI) 1)]; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = stmtscontainpragma_526083_2036603609(loopbody0, ((Tspecialword273003) 182)); if (!(LOC11)) goto LA12; LOC11 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 1))&7U)))!=0); LA12: ; if (!LOC11) goto LA13; { NIM_BOOL LOC17; NI LOC18; LOC17 = (NIM_BOOL)0; LOC18 = (NI)0; LOC18 = len_291081_850551059(loopbody0); LOC17 = (LOC18 == ((NI) 2)); if (!(LOC17)) goto LA19; LOC17 = ((*(*loopbody0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)); LA19: ; if (!LOC17) goto LA20; loopbody0 = (*loopbody0).kindU.S6.sons->data[((NI) 1)]; } LA20: ; gencomputedgoto_543744_839829468(p0, loopbody0); } goto LA9; LA13: ; { genstmts_537244_839829468(p0, loopbody0); } LA9: ; { TY531289 LOC27; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 19))&31U)))!=0)) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_581), LOC27, 0); } LA25: ; endblock_542060_839829468(p0); (*p0).breakidx = oldbreakidx_544011_839829468; (*p0).withinloop -= ((NI) 1); } N_NIMCALL(void, gengotovar_542258_839829468)(Tcproc527021* p0, Tnode290802* value0) { { if (!!(((*value0).kind >= ((Tnodekind290020) 5) && (*value0).kind <= ((Tnodekind290020) 15)))) goto LA3; localerror_194085_155036129((*value0).info, ((NimStringDesc*) &T839829468_582)); } goto LA1; LA3: ; { TY177507 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_177401_2381377266((*value0).kindU.S1.intval); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_583), LOC6, 1); } LA1: ; } N_NIMCALL(void, varindynamiclib_536812_839829468)(Tcgen527027* m0, Tsym290834* sym0) { Tlib290820* lib0; Ropeobj177006* extname0; Ropeobj177006* tmp0; TY533235 LOC1; NimStringDesc* LOC2; TY530811 LOC3; lib0 = (*sym0).annex; extname0 = (*sym0).loc.r; loaddynamiclib_557481_839829468(m0, lib0); (*sym0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 0))%(sizeof(NU16)*8)); tmp0 = mangledynlibproc_536816_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0); (*m0).labels += ((NI) 2); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = tmp0; LOC1[1] = gettypedesc_533673_839829468(m0, (*sym0).typ); LOC1[2] = (*lib0).name; LOC2 = (NimStringDesc*)0; LOC2 = HEX24_177856_2381377266(extname0); LOC1[3] = makecstring_189638_155036129(LOC2); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_584), LOC1, 4); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = (*sym0).loc.r; LOC3[1] = gettypedesc_533673_839829468(m0, (*sym0).loc.t); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_585), LOC3, 2); } N_NIMCALL(void, assignglobalvar_536819_839829468)(Tcproc527021* p0, Tsym290834* s0) { { { Ropeobj177006* LOC5; if (!((*s0).loc.k == ((Tlockind290808) 0))) goto LA3; LOC5 = (Ropeobj177006*)0; LOC5 = manglename_531205_839829468(s0); fillloc_530282_839829468((&(*s0).loc), ((Tlockind290808) 3), (*s0).typ, LOC5, ((Tstorageloc290812) 3)); } LA3: ; { Tcgen527027* q0; if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA8; q0 = findpendingmodule_530241_839829468((*p0).module, s0); { NIM_BOOL LOC12; NIM_BOOL LOC14; LOC12 = (NIM_BOOL)0; LOC12 = !((q0 == NIM_NIL)); if (!(LOC12)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*s0).Sup.id); LOC12 = !(LOC14); LA13: ; if (!LOC12) goto LA15; varindynamiclib_536812_839829468(q0, s0); } goto LA10; LA15: ; { asgnRefNoCycle((void**) (&(*s0).loc.r), mangledynlibproc_536816_839829468(s0)); } LA10: ; goto BeforeRet; } LA8: ; useheader_530369_839829468((*p0).module, s0); { if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA20; goto BeforeRet; } LA20: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0)) goto LA24; declarethreadvar_536676_839829468((*p0).module, s0, (((*s0).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0)); } goto LA22; LA24: ; { Ropeobj177006* decl0; Ropeobj177006* td0; decl0 = NIM_NIL; td0 = gettypedesc_533673_839829468((*p0).module, (*s0).loc.t); { TY177507 LOC43; if (!(*s0).constraint == 0) goto LA29; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0)) goto LA33; add_177487_2381377266(&decl0, ((NimStringDesc*) &T839829468_240)); } LA33: ; add_177482_2381377266(&decl0, td0); { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 8))&31U)))!=0)) goto LA37; add_177487_2381377266(&decl0, ((NimStringDesc*) &T839829468_121)); } LA37: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 7))&31U)))!=0)) goto LA41; add_177487_2381377266(&decl0, ((NimStringDesc*) &T839829468_122)); } LA41: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = (*s0).loc.r; addf_178205_2381377266(&decl0, ((NimStringDesc*) &T839829468_242), LOC43, 1); } goto LA27; LA29: ; { NimStringDesc* LOC45; TY530811 LOC46; LOC45 = (NimStringDesc*)0; LOC45 = rawNewString((*(*s0).constraint).kindU.S3.strval->Sup.len + 3); appendString(LOC45, (*(*s0).constraint).kindU.S3.strval); appendString(LOC45, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC46, 0, sizeof(LOC46)); LOC46[0] = td0; LOC46[1] = (*s0).loc.r; decl0 = HEX25_177905_2381377266(LOC45, LOC46, 2); } LA27: ; add_177482_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 9))- 0], decl0); } LA22: ; { if (!(((NI) 0) < (*p0).withinloop)) goto LA49; resetloc_536350_839829468(p0, (&(*s0).loc)); } LA49: ; { TY533238 LOC55; NimStringDesc* LOC56; NimStringDesc* LOC57; if (!(((*(*(*p0).module).module).options & 163840) == 163840)) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC56 = (NimStringDesc*)0; LOC56 = rawNewString((*(*(*s0).owner).name).s->Sup.len + (*(*s0).name).s->Sup.len + 1); appendString(LOC56, (*(*(*s0).owner).name).s); appendChar(LOC56, 46); appendString(LOC56, (*(*s0).name).s); LOC57 = (NimStringDesc*)0; LOC57 = nsuNormalize(LOC56); LOC55[0] = makecstring_189638_155036129(LOC57); LOC55[1] = (*s0).loc.r; LOC55[2] = gentypeinfo_533941_839829468((*p0).module, (*s0).typ); appcg_530632_839829468((*p0).module, &(*(*p0).module).s[(((Tcfilesection527005) 15))- 0], ((NimStringDesc*) &T839829468_586), LOC55, 3); } LA53: ; }BeforeRet: ; } N_NIMCALL(Ropeobj177006*, gentraverseprocforglobal_536032_839829468)(Tcgen527027* m0, Tsym290834* s0) { Ropeobj177006* result0; Ropeobj177006* LOC1; Ttraversalclosure535019 c0; Tcproc527021* p0; Ropeobj177006* sloc0; Ropeobj177006* header0; TY177507 LOC8; Ropeobj177006* generatedproc0; TY533235 LOC9; Ropeobj177006** LOC10; Ropeobj177006** LOC11; Ropeobj177006** LOC12; TY177507 LOC13; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = gentypeinfo_533941_839829468(m0, (*s0).loc.t); memset((void*)(&c0), 0, sizeof(c0)); p0 = newproc_527206_3723162438(NIM_NIL, m0); sloc0 = (*s0).loc.r; result0 = gettempname_531598_839829468(m0); { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (((*s0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0); if (!(LOC4)) goto LA5; LOC4 = emulatedthreadvars_530949_839829468(); LA5: ; if (!LOC4) goto LA6; accessthreadlocalvar_530945_839829468(p0, s0); sloc0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_288), sloc0); } LA6: ; c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_587)); c0.p = p0; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = result0; header0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_588), LOC8, 1); gentraverseproc_535022_839829468((&c0), sloc0, (*s0).loc.t); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = header0; LOC10 = (Ropeobj177006**)0; LOC10 = s_527179_3723162438(p0, ((Tcprocsection527011) 0)); LOC9[1] = (*LOC10); LOC11 = (Ropeobj177006**)0; LOC11 = s_527179_3723162438(p0, ((Tcprocsection527011) 1)); LOC9[2] = (*LOC11); LOC12 = (Ropeobj177006**)0; LOC12 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); LOC9[3] = (*LOC12); generatedproc0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_190), LOC9, 4); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = header0; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC13, 1); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], generatedproc0); return result0; } N_NIMCALL(void, registergcroot_541762_839829468)(Tcproc527021* p0, Tsym290834* v0) { { NIM_BOOL LOC3; Ropeobj177006* prc0; Ropeobj177006** LOC7; TY177507 LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((240 &(1U<<((NU)(gselectedgc_168133_2607990831)&7U)))!=0); if (!(LOC3)) goto LA4; LOC3 = containsgarbagecollectedref_318117_3876443242((*v0).loc.t); LA4: ; if (!LOC3) goto LA5; prc0 = gentraverseprocforglobal_536032_839829468((*p0).module, v0); LOC7 = (Ropeobj177006**)0; LOC7 = procsec_527194_3723162438((*(*p0).module).initproc, ((Tcprocsection527011) 1)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = prc0; appcg_530632_839829468((*p0).module, LOC7, ((NimStringDesc*) &T839829468_589), LOC8, 1); } LA5: ; } static N_INLINE(NIM_BOOL, isassignedimmediately_541781_839829468)(Tnode290802* n0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!((*n0).kind == ((Tnodekind290020) 1))) goto LA3; result0 = NIM_FALSE; goto BeforeRet; } LA3: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = isinvalidreturntype_531550_839829468((*n0).typ); if (!LOC7) goto LA8; result0 = NIM_FALSE; goto BeforeRet; } LA8: ; result0 = NIM_TRUE; }BeforeRet: ; return result0; } N_NIMCALL(void, genasgncall_541695_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) { { Ttype290840* LOC3; LOC3 = (Ttype290840*)0; LOC3 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, 2048); if (!((*LOC3).callconv == ((Tcallingconvention290002) 8))) goto LA4; genclosurecall_538452_839829468(p0, le0, ri0, d0); } goto LA1; LA4: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC7)) goto LA8; LOC7 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; geninfixcall_539929_839829468(p0, le0, ri0, d0); } goto LA1; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC12)) goto LA13; LOC12 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 28))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; gennamedparamcall_540616_839829468(p0, ri0, d0); } goto LA1; LA14: ; { genprefixcall_537960_839829468(p0, le0, ri0, d0); } LA1: ; poststmtactions_530942_839829468(p0); } static N_INLINE(void, loadinto_541928_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* a0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; LOC3 = (NIM_BOOL)0; LOC3 = ((*ri0).kind == ((Tnodekind290020) 27) || (*ri0).kind == ((Tnodekind290020) 29) || (*ri0).kind == ((Tnodekind290020) 30) || (*ri0).kind == ((Tnodekind290020) 31) || (*ri0).kind == ((Tnodekind290020) 26) || (*ri0).kind == ((Tnodekind290020) 28) || (*ri0).kind == ((Tnodekind290020) 32)); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = !(((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3))); if (LOC5) goto LA6; LOC5 = ((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).magic == ((Tmagic290524) 0)); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; genasgncall_541695_839829468(p0, le0, ri0, a0); } goto LA1; LA7: ; { if (!((*ri0).kind == ((Tnodekind290020) 47) || (*ri0).kind == ((Tnodekind290020) 65))) goto LA10; genderef_541921_839829468(p0, ri0, a0, NIM_TRUE); } goto LA1; LA10: ; { expr_537248_839829468(p0, ri0, a0); } LA1: ; } N_NIMCALL(void, gensinglevar_542276_839829468)(Tcproc527021* p0, Tnode290802* a0) { Tsym290834* v0; Tcproc527021* targetproc0; { v0 = (*(*a0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { if (!!(((1082130432 & (*v0).flags) == 0))) goto LA3; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 30))&31U)))!=0)) goto LA7; gengotovar_542258_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 2)]); } LA7: ; goto BeforeRet; } LA3: ; targetproc0 = p0; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 3))&31U)))!=0)) goto LA11; { NIM_BOOL LOC15; NIM_BOOL LOC16; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC16 = (((*v0).flags & 96) == 32); if (!(LOC16)) goto LA17; LOC16 = ((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1)); LA17: ; LOC15 = LOC16; if (!(LOC15)) goto LA18; LOC15 = !((((*v0).loc.flags & 72) == 0)); LA18: ; if (!LOC15) goto LA19; goto BeforeRet; } LA19: ; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)) goto LA23; targetproc0 = (*(*p0).module).preinitproc; } LA23: ; assignglobalvar_536819_839829468(targetproc0, v0); genobjectinit_536242_839829468((*(*p0).module).preinitproc, ((Tcprocsection527011) 1), (*v0).typ, (&(*v0).loc), NIM_TRUE); { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = (((*v0).flags &(1U<<((NU)(((Tsymflag290184) 6))&31U)))!=0); if (!(LOC27)) goto LA28; LOC27 = !((generatedheader_530201_839829468 == NIM_NIL)); LA28: ; if (!LOC27) goto LA29; genvarprototypeaux_542254_839829468(generatedheader_530201_839829468, v0); } LA29: ; registergcroot_541762_839829468(p0, v0); } goto LA9; LA11: ; { Tnode290802* value0; NIM_BOOL imm0; value0 = (*a0).kindU.S6.sons->data[((NI) 2)]; imm0 = isassignedimmediately_541781_839829468(value0); { NIM_BOOL LOC34; NIM_BOOL LOC35; NIM_BOOL LOC36; NIM_BOOL LOC38; NIM_BOOL LOC42; Ropeobj177006* decl0; Tloc290816 tmp0; LOC34 = (NIM_BOOL)0; LOC35 = (NIM_BOOL)0; LOC36 = (NIM_BOOL)0; LOC36 = imm0; if (!(LOC36)) goto LA37; LOC38 = (NIM_BOOL)0; LOC38 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC38) goto LA39; LOC38 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA39: ; LOC36 = LOC38; LA37: ; LOC35 = LOC36; if (!(LOC35)) goto LA40; LOC35 = ((*p0).splitdecls == ((NI) 0)); LA40: ; LOC34 = LOC35; if (!(LOC34)) goto LA41; LOC42 = (NIM_BOOL)0; LOC42 = containshiddenpointer_318120_3876443242((*v0).typ); LOC34 = !(LOC42); LA41: ; if (!LOC34) goto LA43; genlinedir_530823_839829468(p0, a0); decl0 = localvardecl_536532_839829468(p0, v0); memset((void*)(&tmp0), 0, sizeof(tmp0)); { NIM_BOOL LOC47; NIM_BOOL LOC48; Tnode290802* LOC50; Tnode290802* LOC52; Ropeobj177006* params0; Ttype290840* typ0; TY530811 LOC66; LOC47 = (NIM_BOOL)0; LOC48 = (NIM_BOOL)0; LOC48 = ((*value0).kind == ((Tnodekind290020) 27) || (*value0).kind == ((Tnodekind290020) 29) || (*value0).kind == ((Tnodekind290020) 30) || (*value0).kind == ((Tnodekind290020) 31) || (*value0).kind == ((Tnodekind290020) 26) || (*value0).kind == ((Tnodekind290020) 28) || (*value0).kind == ((Tnodekind290020) 32)); if (!(LOC48)) goto LA49; LOC50 = (Tnode290802*)0; LOC50 = HEX5BHEX5D_291238_850551059(value0, ((NI) 0)); LOC48 = ((*LOC50).kind == ((Tnodekind290020) 3)); LA49: ; LOC47 = LOC48; if (!(LOC47)) goto LA51; LOC52 = (Tnode290802*)0; LOC52 = HEX5BHEX5D_291238_850551059(value0, ((NI) 0)); LOC47 = (((*(*LOC52).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 24))&31U)))!=0); LA51: ; if (!LOC47) goto LA53; params0 = (Ropeobj177006*)0; typ0 = skiptypes_294099_850551059((*(*value0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { NI i_542619_839829468; NI HEX3Atmp_542825_839829468; NI LOC56; NI res_542828_839829468; i_542619_839829468 = (NI)0; HEX3Atmp_542825_839829468 = (NI)0; LOC56 = (NI)0; LOC56 = len_291081_850551059(value0); HEX3Atmp_542825_839829468 = (LOC56 - 1); res_542828_839829468 = ((NI) 1); { while (1) { Ropeobj177006* LOC65; if (!(res_542828_839829468 <= HEX3Atmp_542825_839829468)) goto LA58; i_542619_839829468 = res_542828_839829468; { TY531289 LOC63; Ropeobj177006* LOC64; if (!!((params0 == NIM_NIL))) goto LA61; memset((void*)LOC63, 0, sizeof(LOC63)); LOC64 = (Ropeobj177006*)0; LOC64 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC63, 0); add_177482_2381377266(&params0, LOC64); } LA61: ; LOC65 = (Ropeobj177006*)0; LOC65 = genotherarg_537277_839829468(p0, value0, i_542619_839829468, typ0); add_177482_2381377266(&params0, LOC65); res_542828_839829468 += ((NI) 1); } LA58: ; } } memset((void*)LOC66, 0, sizeof(LOC66)); LOC66[0] = decl0; LOC66[1] = params0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_590), LOC66, 2); } goto LA45; LA53: ; { TY530811 LOC68; initlocexprsingleuse_537289_839829468(p0, value0, (&tmp0)); memset((void*)LOC68, 0, sizeof(LOC68)); LOC68[0] = decl0; LOC68[1] = rdloc_536188_839829468((&tmp0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_591), LOC68, 2); } LA45: ; goto BeforeRet; } LA43: ; assignlocalvar_536614_839829468(p0, v0); initlocalvar_536398_839829468(p0, v0, imm0); } LA9: ; { if (!!(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1)))) goto LA71; genlinedir_530823_839829468(targetproc0, a0); loadinto_541928_839829468(targetproc0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&(*v0).loc)); } LA71: ; }BeforeRet: ; } N_NIMCALL(void, genclosurevar_542832_839829468)(Tcproc527021* p0, Tnode290802* a0) { NIM_BOOL immediateasgn0; immediateasgn0 = !(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1))); { Tloc290816 v0; if (!immediateasgn0) goto LA3; memset((void*)(&v0), 0, sizeof(v0)); initlocexpr_537283_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (&v0)); genlinedir_530823_839829468(p0, a0); loadinto_541928_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&v0)); } LA3: ; } N_NIMCALL(void, genvartuple_541794_839829468)(Tcproc527021* p0, Tnode290802* n0) { Tloc290816 tup0; Tloc290816 field0; NI L0; NIM_BOOL uselowering0; Ttype290840* t0; { memset((void*)(&tup0), 0, sizeof(tup0)); memset((void*)(&field0), 0, sizeof(field0)); { if (!!(((*n0).kind == ((Tnodekind290020) 36)))) goto LA3; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592)); } LA3: ; L0 = sonslen_293351_850551059(n0); uselowering0 = NIM_FALSE; { NI i_541822_839829468; NI HEX3Atmp_541905_839829468; NI res_541908_839829468; i_541822_839829468 = (NI)0; HEX3Atmp_541905_839829468 = (NI)0; HEX3Atmp_541905_839829468 = (NI)(L0 - ((NI) 3)); res_541908_839829468 = ((NI) 0); { while (1) { if (!(res_541908_839829468 <= HEX3Atmp_541905_839829468)) goto LA7; i_541822_839829468 = res_541908_839829468; { Tnode290802* LOC10; LOC10 = (Tnode290802*)0; LOC10 = HEX5BHEX5D_291238_850551059(n0, i_541822_839829468); if (!!(((*LOC10).kind == ((Tnodekind290020) 3)))) goto LA11; uselowering0 = NIM_TRUE; goto LA5; } LA11: ; res_541908_839829468 += ((NI) 1); } LA7: ; } } LA5: ; { Tnode290802* LOC17; if (!uselowering0) goto LA15; LOC17 = (Tnode290802*)0; LOC17 = lowertupleunpacking_431037_2218250499(n0, (*p0).prc); genstmts_537244_839829468(p0, LOC17); goto BeforeRet; } LA15: ; genlinedir_530823_839829468(p0, n0); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(L0 - ((NI) 1))], (&tup0)); t0 = getuniquetype_526640_2036603609(tup0.t); { NI i_541846_839829468; NI HEX3Atmp_541914_839829468; NI res_541917_839829468; i_541846_839829468 = (NI)0; HEX3Atmp_541914_839829468 = (NI)0; HEX3Atmp_541914_839829468 = (NI)(L0 - ((NI) 3)); res_541917_839829468 = ((NI) 0); { while (1) { if (!(res_541917_839829468 <= HEX3Atmp_541914_839829468)) goto LA20; i_541846_839829468 = res_541917_839829468; { Tsym290834* v0; v0 = (*(*n0).kindU.S6.sons->data[i_541846_839829468]).kindU.S4.sym; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 23))&31U)))!=0)) goto LA24; goto LA21; } LA24: ; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 3))&31U)))!=0)) goto LA28; assignglobalvar_536819_839829468(p0, v0); genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 1), (*v0).typ, (&(*v0).loc), NIM_TRUE); registergcroot_541762_839829468(p0, v0); } goto LA26; LA28: ; { Tnode290802* LOC31; NIM_BOOL LOC32; assignlocalvar_536614_839829468(p0, v0); LOC31 = (Tnode290802*)0; LOC31 = HEX5BHEX5D_291238_850551059(n0, (NI)(L0 - ((NI) 1))); LOC32 = (NIM_BOOL)0; LOC32 = isassignedimmediately_541781_839829468(LOC31); initlocalvar_536398_839829468(p0, v0, LOC32); } LA26: ; initloc_530273_839829468((&field0), ((Tlockind290808) 6), (*t0).sons->data[i_541846_839829468], tup0.s); { TY530811 LOC37; if (!((*t0).kind == ((Ttypekind290244) 18))) goto LA35; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = rdloc_536188_839829468((&tup0)); LOC37[1] = rope_177401_2381377266(((NI64) (i_541846_839829468))); field0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_185), LOC37, 2); } goto LA33; LA35: ; { TY530811 LOC43; { if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_541846_839829468]).kind == ((Tnodekind290020) 3)))) goto LA41; internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592)); } LA41: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = rdloc_536188_839829468((&tup0)); LOC43[1] = manglerecfieldname_532361_839829468((*(*(*t0).n).kindU.S6.sons->data[i_541846_839829468]).kindU.S4.sym, t0); field0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC43, 2); } LA33: ; putlocintodest_537258_839829468(p0, (&(*v0).loc), (&field0)); } LA21: ; res_541917_839829468 += ((NI) 1); } LA20: ; } } }BeforeRet: ; } N_NIMCALL(void, genvarstmt_542854_839829468)(Tcproc527021* p0, Tnode290802* n0) { { NI i_542869_839829468; NI HEX3Atmp_542902_839829468; NI LOC2; NI res_542905_839829468; i_542869_839829468 = (NI)0; HEX3Atmp_542902_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(n0); HEX3Atmp_542902_839829468 = (NI)(LOC2 - ((NI) 1)); res_542905_839829468 = ((NI) 0); { while (1) { if (!(res_542905_839829468 <= HEX3Atmp_542902_839829468)) goto LA4; i_542869_839829468 = res_542905_839829468; { Tnode290802* a0; a0 = (*n0).kindU.S6.sons->data[i_542869_839829468]; { if (!((*a0).kind == ((Tnodekind290020) 125))) goto LA8; goto LA5; } LA8: ; { if (!((*a0).kind == ((Tnodekind290020) 35))) goto LA12; { if (!((*(*a0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3))) goto LA16; gensinglevar_542276_839829468(p0, a0); } goto LA14; LA16: ; { genclosurevar_542832_839829468(p0, a0); } LA14: ; } goto LA10; LA12: ; { genvartuple_541794_839829468(p0, a0); } LA10: ; } LA5: ; res_542905_839829468 += ((NI) 1); } LA4: ; } } } static N_INLINE(NIM_BOOL, emitlazily_530248_839829468)(Tsym290834* s0) { NIM_BOOL result0; NIM_BOOL LOC1; Tsym290834* LOC3; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 2))&63U)))!=0); if (LOC1) goto LA2; LOC3 = (Tsym290834*)0; LOC3 = getmodule_297123_2984716966(s0); LOC1 = (((*LOC3).flags &(1U<<((NU)(((Tsymflag290184) 25))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, genconststmt_542909_839829468)(Tcproc527021* p0, Tnode290802* t0) { { NI i_542924_839829468; NI HEX3Atmp_542975_839829468; NI LOC2; NI res_542978_839829468; i_542924_839829468 = (NI)0; HEX3Atmp_542975_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(t0); HEX3Atmp_542975_839829468 = (NI)(LOC2 - ((NI) 1)); res_542978_839829468 = ((NI) 0); { while (1) { if (!(res_542978_839829468 <= HEX3Atmp_542975_839829468)) goto LA4; i_542924_839829468 = res_542978_839829468; { Tnode290802* it0; Tsym290834* c0; it0 = (*t0).kindU.S6.sons->data[i_542924_839829468]; { if (!((*it0).kind == ((Tnodekind290020) 125))) goto LA8; goto LA5; } LA8: ; { if (!!(((*it0).kind == ((Tnodekind290020) 102)))) goto LA12; internalerror_194100_155036129((*t0).info, ((NimStringDesc*) &T839829468_593)); } LA12: ; c0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NIM_BOOL LOC16; LOC16 = (NIM_BOOL)0; LOC16 = containscompiletimeonly_326721_3876443242((*c0).typ); if (!LOC16) goto LA17; goto LA5; } goto LA14; LA17: ; { NIM_BOOL LOC20; NIM_BOOL LOC21; NI LOC24; LOC20 = (NIM_BOOL)0; LOC21 = (NIM_BOOL)0; LOC21 = ((17629200 &((NU64)1<<((NU)((*(*c0).typ).kind)&63U)))!=0); if (!(LOC21)) goto LA22; LOC21 = !((((*c0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)); LA22: ; LOC20 = LOC21; if (!(LOC20)) goto LA23; LOC24 = (NI)0; LOC24 = len_291081_850551059((*c0).ast); LOC20 = !((LOC24 == ((NI) 0))); LA23: ; if (!LOC20) goto LA25; { NIM_BOOL LOC29; LOC29 = (NIM_BOOL)0; LOC29 = emitlazily_530248_839829468(c0); if (!!(LOC29)) goto LA30; requestconstimpl_537240_839829468(p0, c0); } LA30: ; } goto LA14; LA25: ; LA14: ; } LA5: ; res_542978_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, gencasestringbranch_545100_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816* e0, Ropeobj177006* labl0, Ropeobj177006** branches0, NI branches0Len0) { Tloc290816 x0; NI length0; memset((void*)(&x0), 0, sizeof(x0)); length0 = sonslen_293351_850551059(b0); { NI i_545122_839829468; NI HEX3Atmp_545410_839829468; NI res_545413_839829468; i_545122_839829468 = (NI)0; HEX3Atmp_545410_839829468 = (NI)0; HEX3Atmp_545410_839829468 = (NI)(length0 - ((NI) 2)); res_545413_839829468 = ((NI) 0); { while (1) { NI j0; NI64 LOC4; TY533238 LOC5; if (!(res_545413_839829468 <= HEX3Atmp_545410_839829468)) goto LA3; i_545122_839829468 = res_545413_839829468; initlocexpr_537283_839829468(p0, (*b0).kindU.S6.sons->data[i_545122_839829468], (&x0)); LOC4 = (NI64)0; LOC4 = hashstring_526100_2036603609((*(*b0).kindU.S6.sons->data[i_545122_839829468]).kindU.S3.strval); j0 = ((NI) ((NI64)(LOC4 & ((NI64) ((branches0Len0-1)))))); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468(e0); LOC5[1] = rdloc_536188_839829468((&x0)); LOC5[2] = labl0; appcg_530632_839829468((*p0).module, &branches0[j0], ((NimStringDesc*) &T839829468_595), LOC5, 3); res_545413_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, exprblock_542103_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { TY531289 LOC1; NI LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0); expr_537248_839829468(p0, n0, d0); endblock_542060_839829468(p0); } N_NIMCALL(Ropeobj177006*, gencasesecondpass_544965_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NI labid0, NI until0) { Ropeobj177006* result0; Ropeobj177006* lend0; result0 = (Ropeobj177006*)0; lend0 = getlabel_537217_839829468(p0); { NI i_544984_839829468; NI res_545017_839829468; i_544984_839829468 = (NI)0; res_545017_839829468 = ((NI) 1); { while (1) { TY177507 LOC10; if (!(res_545017_839829468 <= until0)) goto LA3; i_544984_839829468 = res_545017_839829468; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = ((*d0).k == ((Tlockind290808) 1)); if (!(LOC6)) goto LA7; LOC6 = isemptytype_295441_850551059((*t0).typ); LA7: ; if (!LOC6) goto LA8; (*d0).k = ((Tlockind290808) 0); } LA8: ; memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rope_177401_2381377266(((NI64) ((NI)(labid0 + i_544984_839829468)))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_599), LOC10, 1); { NI length0; TY177507 LOC15; if (!((*(*t0).kindU.S6.sons->data[i_544984_839829468]).kind == ((Tnodekind290020) 85))) goto LA13; length0 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i_544984_839829468]); exprblock_542103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_544984_839829468]).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = lend0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_556), LOC15, 1); } goto LA11; LA13: ; { exprblock_542103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_544984_839829468]).kindU.S6.sons->data[((NI) 0)], d0); } LA11: ; res_545017_839829468 += ((NI) 1); } LA3: ; } } result0 = lend0; return result0; } N_NIMCALL(void, gencasegenericbranch_544910_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816* e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj177006* labl0) { Tloc290816 x0; Tloc290816 y0; NI length0; memset((void*)(&x0), 0, sizeof(x0)); memset((void*)(&y0), 0, sizeof(y0)); length0 = sonslen_293351_850551059(b0); { NI i_544932_839829468; NI HEX3Atmp_544958_839829468; NI res_544961_839829468; i_544932_839829468 = (NI)0; HEX3Atmp_544958_839829468 = (NI)0; HEX3Atmp_544958_839829468 = (NI)(length0 - ((NI) 2)); res_544961_839829468 = ((NI) 0); { while (1) { if (!(res_544961_839829468 <= HEX3Atmp_544958_839829468)) goto LA3; i_544932_839829468 = res_544961_839829468; { TY533235 LOC8; if (!((*(*b0).kindU.S6.sons->data[i_544932_839829468]).kind == ((Tnodekind290020) 44))) goto LA6; initlocexpr_537283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_544932_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0)); initlocexpr_537283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_544932_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdcharloc_536227_839829468(e0); LOC8[1] = rdcharloc_536227_839829468((&x0)); LOC8[2] = rdcharloc_536227_839829468((&y0)); LOC8[3] = labl0; linecg_530707_839829468(p0, ((Tcprocsection527011) 2), rangeformat0, LOC8, 4); } goto LA4; LA6: ; { TY533238 LOC10; initlocexpr_537283_839829468(p0, (*b0).kindU.S6.sons->data[i_544932_839829468], (&x0)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdcharloc_536227_839829468(e0); LOC10[1] = rdcharloc_536227_839829468((&x0)); LOC10[2] = labl0; linecg_530707_839829468(p0, ((Tcprocsection527011) 2), eqformat0, LOC10, 3); } LA4: ; res_544961_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(Ropeobj177006*, genifforcaseuntil_545021_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc290816* a0) { Ropeobj177006* result0; NI labid0; result0 = (Ropeobj177006*)0; labid0 = (*p0).labels; { NI i_545042_839829468; NI res_545083_839829468; i_545042_839829468 = (NI)0; res_545083_839829468 = ((NI) 1); { while (1) { if (!(res_545083_839829468 <= until0)) goto LA3; i_545042_839829468 = res_545083_839829468; (*p0).labels += ((NI) 1); { Ropeobj177006* LOC8; Ropeobj177006* LOC9; if (!((*(*t0).kindU.S6.sons->data[i_545042_839829468]).kind == ((Tnodekind290020) 85))) goto LA6; LOC8 = (Ropeobj177006*)0; LOC8 = rope_177401_2381377266(((NI64) ((*p0).labels))); LOC9 = (Ropeobj177006*)0; LOC9 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC8); gencasegenericbranch_544910_839829468(p0, (*t0).kindU.S6.sons->data[i_545042_839829468], a0, rangeformat0, eqformat0, LOC9); } goto LA4; LA6: ; { TY177507 LOC11; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rope_177401_2381377266(((NI64) ((*p0).labels))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_598), LOC11, 1); } LA4: ; res_545083_839829468 += ((NI) 1); } LA3: ; } } { NI LOC14; NI gototarget0; TY177507 LOC17; TY177507 LOC18; LOC14 = (NI)0; LOC14 = len_291081_850551059(t0); if (!(until0 < (NI)(LOC14 - ((NI) 1)))) goto LA15; (*p0).labels += ((NI) 1); gototarget0 = (*p0).labels; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rope_177401_2381377266(((NI64) (gototarget0))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_598), LOC17, 1); result0 = gencasesecondpass_544965_839829468(p0, t0, d0, ((NI) (labid0)), until0); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rope_177401_2381377266(((NI64) (gototarget0))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_599), LOC18, 1); } goto LA12; LA15: ; { result0 = gencasesecondpass_544965_839829468(p0, t0, d0, ((NI) (labid0)), until0); } LA12: ; return result0; } N_NIMCALL(void, gencasegeneric_545087_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0) { Tloc290816 a0; Ropeobj177006* lend0; NI LOC1; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (NI)0; LOC1 = sonslen_293351_850551059(t0); lend0 = genifforcaseuntil_545021_839829468(p0, t0, d0, rangeformat0, eqformat0, (NI)(LOC1 - ((NI) 1)), (&a0)); fixlabel_537230_839829468(p0, lend0); } N_NIMCALL(void, genstringcase_545417_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) { NI strings0; strings0 = ((NI) 0); { NI i_545435_839829468; NI HEX3Atmp_545550_839829468; NI LOC2; NI res_545553_839829468; i_545435_839829468 = (NI)0; HEX3Atmp_545550_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(t0); HEX3Atmp_545550_839829468 = (NI)(LOC2 - ((NI) 1)); res_545553_839829468 = ((NI) 1); { while (1) { if (!(res_545553_839829468 <= HEX3Atmp_545550_839829468)) goto LA4; i_545435_839829468 = res_545553_839829468; { NI LOC9; if (!((*(*t0).kindU.S6.sons->data[i_545435_839829468]).kind == ((Tnodekind290020) 85))) goto LA7; LOC9 = (NI)0; LOC9 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i_545435_839829468]); strings0 += (NI)(LOC9 - ((NI) 1)); } LA7: ; res_545553_839829468 += ((NI) 1); } LA4: ; } } { NI bitmask0; NI LOC14; TY189350* branches0; Tloc290816 a0; NI labid0; TY530811 LOC26; TY531289 LOC35; Ropeobj177006* lend0; NI LOC42; if (!(((NI) 8) < strings0)) goto LA12; LOC14 = (NI)0; LOC14 = nextpoweroftwo_100629_1009420244(strings0); bitmask0 = (NI)(LOC14 - ((NI) 1)); branches0 = (TY189350*)0; branches0 = (TY189350*) newSeq((&NTI189350), ((NI) ((NI)(bitmask0 + ((NI) 1))))); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); labid0 = (*p0).labels; { NI i_545484_839829468; NI HEX3Atmp_545560_839829468; NI LOC16; NI res_545563_839829468; i_545484_839829468 = (NI)0; HEX3Atmp_545560_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_293351_850551059(t0); HEX3Atmp_545560_839829468 = (NI)(LOC16 - ((NI) 1)); res_545563_839829468 = ((NI) 1); { while (1) { if (!(res_545563_839829468 <= HEX3Atmp_545560_839829468)) goto LA18; i_545484_839829468 = res_545563_839829468; (*p0).labels += ((NI) 1); { Ropeobj177006* LOC23; Ropeobj177006* LOC24; if (!((*(*t0).kindU.S6.sons->data[i_545484_839829468]).kind == ((Tnodekind290020) 85))) goto LA21; LOC23 = (Ropeobj177006*)0; LOC23 = rope_177401_2381377266(((NI64) ((*p0).labels))); LOC24 = (Ropeobj177006*)0; LOC24 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC23); gencasestringbranch_545100_839829468(p0, (*t0).kindU.S6.sons->data[i_545484_839829468], (&a0), LOC24, branches0->data, branches0->Sup.len); } goto LA19; LA21: ; { } LA19: ; res_545563_839829468 += ((NI) 1); } LA18: ; } } memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rdloc_536188_839829468((&a0)); LOC26[1] = rope_177401_2381377266(((NI64) (bitmask0))); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_596), LOC26, 2); { NI j_545518_839829468; NI HEX3Atmp_545568_839829468; NI res_545571_839829468; j_545518_839829468 = (NI)0; HEX3Atmp_545568_839829468 = (NI)0; HEX3Atmp_545568_839829468 = (branches0 ? (branches0->Sup.len-1) : -1); res_545571_839829468 = ((NI) 0); { while (1) { if (!(res_545571_839829468 <= HEX3Atmp_545568_839829468)) goto LA29; j_545518_839829468 = res_545571_839829468; { TY530811 LOC34; if (!!((branches0->data[j_545518_839829468] == NIM_NIL))) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = intliteral_537270_839829468(((NI64) (j_545518_839829468))); LOC34[1] = branches0->data[j_545518_839829468]; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_597), LOC34, 2); } LA32: ; res_545571_839829468 += ((NI) 1); } LA29: ; } } memset((void*)LOC35, 0, sizeof(LOC35)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC35, 0); { NI LOC38; TY177507 LOC41; LOC38 = (NI)0; LOC38 = sonslen_293351_850551059(t0); if (!!(((*(*t0).kindU.S6.sons->data[(NI)(LOC38 - ((NI) 1))]).kind == ((Tnodekind290020) 85)))) goto LA39; memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = rope_177401_2381377266(((NI64) ((*p0).labels))); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_598), LOC41, 1); } LA39: ; LOC42 = (NI)0; LOC42 = sonslen_293351_850551059(t0); lend0 = gencasesecondpass_544965_839829468(p0, t0, d0, ((NI) (labid0)), (NI)(LOC42 - ((NI) 1))); fixlabel_537230_839829468(p0, lend0); } goto LA10; LA12: ; { gencasegeneric_545087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_490), ((NimStringDesc*) &T839829468_595)); } LA10: ; } N_NIMCALL(void, gengotoforcase_543673_839829468)(Tcproc527021* p0, Tnode290802* casestmt0) { { { NI i_543695_839829468; NI HEX3Atmp_543737_839829468; NI LOC2; NI res_543740_839829468; i_543695_839829468 = (NI)0; HEX3Atmp_543737_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_291081_850551059(casestmt0); HEX3Atmp_543737_839829468 = (LOC2 - 1); res_543740_839829468 = ((NI) 1); { while (1) { TY531289 LOC5; NI LOC6; Tnode290802* it0; Tnode290802* LOC16; if (!(res_543740_839829468 <= HEX3Atmp_543737_839829468)) goto LA4; i_543695_839829468 = res_543740_839829468; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (NI)0; LOC6 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC5, 0); it0 = (*casestmt0).kindU.S6.sons->data[i_543695_839829468]; { NI j_543711_839829468; NI HEX3Atmp_543730_839829468; NI LOC8; NI res_543733_839829468; j_543711_839829468 = (NI)0; HEX3Atmp_543730_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = len_291081_850551059(it0); HEX3Atmp_543730_839829468 = (NI)(LOC8 - ((NI) 2)); res_543733_839829468 = ((NI) 0); { while (1) { NI64 val0; TY177507 LOC15; if (!(res_543733_839829468 <= HEX3Atmp_543730_839829468)) goto LA10; j_543711_839829468 = res_543733_839829468; { if (!((*(*it0).kindU.S6.sons->data[j_543711_839829468]).kind == ((Tnodekind290020) 44))) goto LA13; localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579)); goto BeforeRet; } LA13: ; val0 = getordvalue_318129_3876443242((*it0).kindU.S6.sons->data[j_543711_839829468]); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = rope_177401_2381377266(val0); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_602), LOC15, 1); res_543733_839829468 += ((NI) 1); } LA10: ; } } LOC16 = (Tnode290802*)0; LOC16 = lastson_293364_850551059(it0); genstmts_537244_839829468(p0, LOC16); endblock_542060_839829468(p0); res_543740_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; } N_NIMCALL(NIM_BOOL, branchhastoobigrange_545576_839829468)(Tnode290802* b0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { NI i_545591_839829468; NI HEX3Atmp_545609_839829468; NI LOC2; NI res_545612_839829468; i_545591_839829468 = (NI)0; HEX3Atmp_545609_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(b0); HEX3Atmp_545609_839829468 = (NI)(LOC2 - ((NI) 2)); res_545612_839829468 = ((NI) 0); { while (1) { if (!(res_545612_839829468 <= HEX3Atmp_545609_839829468)) goto LA4; i_545591_839829468 = res_545612_839829468; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*b0).kindU.S6.sons->data[i_545591_839829468]).kind == ((Tnodekind290020) 44)); if (!(LOC7)) goto LA8; LOC7 = (IL64(256) < (NI64)((*(*(*b0).kindU.S6.sons->data[i_545591_839829468]).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval - (*(*(*b0).kindU.S6.sons->data[i_545591_839829468]).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval)); LA8: ; if (!LOC7) goto LA9; result0 = NIM_TRUE; goto BeforeRet; } LA9: ; res_545612_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; return result0; } N_NIMCALL(NI, ifswitchsplitpoint_545616_839829468)(Tcproc527021* p0, Tnode290802* n0) { NI result0; result0 = (NI)0; { NI i_545631_839829468; NI HEX3Atmp_545655_839829468; NI LOC2; NI res_545658_839829468; i_545631_839829468 = (NI)0; HEX3Atmp_545655_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_291081_850551059(n0); HEX3Atmp_545655_839829468 = (NI)(LOC2 - ((NI) 1)); res_545658_839829468 = ((NI) 1); { while (1) { Tnode290802* branch0; Tnode290802* stmtblock0; if (!(res_545658_839829468 <= HEX3Atmp_545655_839829468)) goto LA4; i_545631_839829468 = res_545658_839829468; branch0 = HEX5BHEX5D_291238_850551059(n0, i_545631_839829468); stmtblock0 = lastson_293364_850551059(branch0); { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = stmtscontainpragma_526083_2036603609(stmtblock0, ((Tspecialword273003) 181)); if (!LOC7) goto LA8; result0 = i_545631_839829468; } goto LA5; LA8: ; { if (!!(((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 0))&7U)))!=0))) goto LA11; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = ((*branch0).kind == ((Tnodekind290020) 85)); if (!(LOC15)) goto LA16; LOC15 = branchhastoobigrange_545576_839829468(branch0); LA16: ; if (!LOC15) goto LA17; result0 = i_545631_839829468; } LA17: ; } goto LA5; LA11: ; LA5: ; res_545658_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genordinalcase_545725_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { NI splitpoint0; Tloc290816 a0; Ropeobj177006* lend0; splitpoint0 = ifswitchsplitpoint_545616_839829468(p0, n0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); { if (!(((NI) 0) < splitpoint0)) goto LA3; lend0 = genifforcaseuntil_545021_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601), splitpoint0, (&a0)); } goto LA1; LA3: ; { lend0 = NIM_NIL; } LA1: ; { NI LOC8; TY177507 LOC11; NIM_BOOL hasdefault0; TY531289 LOC37; LOC8 = (NI)0; LOC8 = len_291081_850551059(n0); if (!((NI)(splitpoint0 + ((NI) 1)) < LOC8)) goto LA9; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdcharloc_536227_839829468((&a0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_603), LOC11, 1); hasdefault0 = NIM_FALSE; { NI i_545758_839829468; NI HEX3Atmp_545817_839829468; NI HEX3Atmp_545818_839829468; NI LOC13; NI res_545821_839829468; i_545758_839829468 = (NI)0; HEX3Atmp_545817_839829468 = (NI)0; HEX3Atmp_545818_839829468 = (NI)0; HEX3Atmp_545817_839829468 = (NI)(splitpoint0 + ((NI) 1)); LOC13 = (NI)0; LOC13 = len_291081_850551059(n0); HEX3Atmp_545818_839829468 = (LOC13 - 1); res_545821_839829468 = HEX3Atmp_545817_839829468; { while (1) { Tnode290802* branch0; Tnode290802* LOC28; TY531289 LOC29; if (!(res_545821_839829468 <= HEX3Atmp_545818_839829468)) goto LA15; i_545758_839829468 = res_545821_839829468; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = ((*d0).k == ((Tlockind290808) 1)); if (!(LOC18)) goto LA19; LOC18 = isemptytype_295441_850551059((*n0).typ); LA19: ; if (!LOC18) goto LA20; (*d0).k = ((Tlockind290808) 0); } LA20: ; branch0 = HEX5BHEX5D_291238_850551059(n0, i_545758_839829468); { if (!((*branch0).kind == ((Tnodekind290020) 85))) goto LA24; gencaserange_535028_839829468(p0, branch0); } goto LA22; LA24: ; { TY531289 LOC27; memset((void*)LOC27, 0, sizeof(LOC27)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_181), LOC27, 0); hasdefault0 = NIM_TRUE; } LA22: ; LOC28 = (Tnode290802*)0; LOC28 = lastson_293364_850551059(branch0); exprblock_542103_839829468(p0, LOC28, d0); memset((void*)LOC29, 0, sizeof(LOC29)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_182), LOC29, 0); res_545821_839829468 += ((NI) 1); } LA15: ; } } { NIM_BOOL LOC32; TY531289 LOC36; LOC32 = (NIM_BOOL)0; LOC32 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 3))&7U)))!=0); if (!(LOC32)) goto LA33; LOC32 = !(hasdefault0); LA33: ; if (!LOC32) goto LA34; memset((void*)LOC36, 0, sizeof(LOC36)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_604), LOC36, 0); } LA34: ; memset((void*)LOC37, 0, sizeof(LOC37)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC37, 0); } LA9: ; { if (!!((lend0 == NIM_NIL))) goto LA40; fixlabel_537230_839829468(p0, lend0); } LA40: ; } N_NIMCALL(void, gencase_545827_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) { Ttype290840* LOC8; genlinedir_530823_839829468(p0, t0); { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_295441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind290808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; LOC8 = (Ttype290840*)0; LOC8 = skiptypes_294099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440)); switch ((*LOC8).kind) { case ((Ttypekind290244) 28): { genstringcase_545417_839829468(p0, t0, d0); } break; case ((Ttypekind290244) 36) ... ((Ttypekind290244) 39): { gencasegeneric_545087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601)); } break; default: { { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC14)) goto LA15; LOC14 = (((*(*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 30))&31U)))!=0); LA15: ; if (!LOC14) goto LA16; gengotoforcase_543673_839829468(p0, t0); } goto LA12; LA16: ; { genordinalcase_545725_839829468(p0, t0, d0); } LA12: ; } break; } } static N_INLINE(Tnode290802*, pop_316246_1689653243)(Tnodeseq290796** s0) { Tnode290802* result0; NI L0; result0 = (Tnode290802*)0; L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1)); result0 = (*s0)->data[L0]; (*s0) = (Tnodeseq290796*) setLengthSeq(&((*s0))->Sup, sizeof(Tnode290802*), ((NI) (L0))); return result0; } N_NIMCALL(void, blockleaveactions_543442_839829468)(Tcproc527021* p0, NI howmanytrys0, NI howmanyexcepts0) { Tnodeseq290796* stack0; NI alreadypoppedcnt0; stack0 = (Tnodeseq290796*)0; stack0 = (Tnodeseq290796*) newSeq((&NTI290796), ((NI) 0)); alreadypoppedcnt0 = (*p0).inexceptblock; { NI i_543471_839829468; NI res_543596_839829468; i_543471_839829468 = (NI)0; res_543596_839829468 = ((NI) 1); { while (1) { Tnode290802* trystmt0; Tnode290802* finallystmt0; if (!(res_543596_839829468 <= howmanytrys0)) goto LA3; i_543471_839829468 = res_543596_839829468; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC6) goto LA7; LOC6 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA7: ; if (!!(LOC6)) goto LA8; { if (!(((NI) 0) < alreadypoppedcnt0)) goto LA12; alreadypoppedcnt0 -= ((NI) 1); } goto LA10; LA12: ; { TY531289 LOC15; memset((void*)LOC15, 0, sizeof(LOC15)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_605), LOC15, 0); } LA10: ; } LA8: ; trystmt0 = pop_316246_1689653243((&(*p0).nestedtrystmts)); stack0 = (Tnodeseq290796*) incrSeqV2(&(stack0)->Sup, sizeof(Tnode290802*)); asgnRefNoCycle((void**) (&stack0->data[stack0->Sup.len]), trystmt0); ++stack0->Sup.len; finallystmt0 = lastson_293364_850551059(trystmt0); { if (!((*finallystmt0).kind == ((Tnodekind290020) 107))) goto LA18; genstmts_537244_839829468(p0, (*finallystmt0).kindU.S6.sons->data[((NI) 0)]); } LA18: ; res_543596_839829468 += ((NI) 1); } LA3: ; } } { NI i_543546_839829468; NI HEX3Atmp_543601_839829468; NI res_543604_839829468; i_543546_839829468 = (NI)0; HEX3Atmp_543601_839829468 = (NI)0; HEX3Atmp_543601_839829468 = (NI)(howmanytrys0 - ((NI) 1)); res_543604_839829468 = HEX3Atmp_543601_839829468; { while (1) { if (!(((NI) 0) <= res_543604_839829468)) goto LA22; i_543546_839829468 = res_543604_839829468; (*p0).nestedtrystmts = (Tnodeseq290796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode290802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), stack0->data[i_543546_839829468]); ++(*p0).nestedtrystmts->Sup.len; res_543604_839829468 -= ((NI) 1); } LA22: ; } } { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC25) goto LA26; LOC25 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA26: ; if (!!(LOC25)) goto LA27; { NI i_543587_839829468; NI HEX3Atmp_543610_839829468; NI res_543613_839829468; i_543587_839829468 = (NI)0; HEX3Atmp_543610_839829468 = (NI)0; HEX3Atmp_543610_839829468 = (NI)(howmanyexcepts0 - ((NI) 1)); res_543613_839829468 = HEX3Atmp_543610_839829468; { while (1) { TY531289 LOC32; if (!(((NI) 0) <= res_543613_839829468)) goto LA31; i_543587_839829468 = res_543613_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC32, 0); res_543613_839829468 -= ((NI) 1); } LA31: ; } } } LA27: ; } N_NIMCALL(void, genreturnstmt_543617_839829468)(Tcproc527021* p0, Tnode290802* t0) { TY531289 LOC14; { { if (!(((*t0).flags &(1U<<((NU)(((Tnodeflag290427) 14))&15U)))!=0)) goto LA3; goto BeforeRet; } LA3: ; (*p0).beforeretneeded = NIM_TRUE; genlinedir_530823_839829468(p0, t0); { if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA7; genstmts_537244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)]); } LA7: ; blockleaveactions_543442_839829468(p0, ((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0), (*p0).inexceptblock); { Ropeobj177006* safepoint0; TY177507 LOC13; if (!(((NI) 0) < ((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0))) goto LA11; safepoint0 = (*p0).finallysafepoints->data[(NI)(((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0) - ((NI) 1))]; memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_607), LOC13, 1); } LA11: ; memset((void*)LOC14, 0, sizeof(LOC14)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_608), LOC14, 0); }BeforeRet: ; } N_NIMCALL(void, genbreakstmt_544444_839829468)(Tcproc527021* p0, Tnode290802* t0) { NI idx0; Ropeobj177006* label0; TY177507 LOC16; idx0 = (*p0).breakidx; { Tsym290834* sym0; if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA3; sym0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; idx0 = (NI)((*sym0).position - ((NI) 1)); } goto LA1; LA3: ; { { while (1) { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = (((NI) 0) <= idx0); if (!(LOC8)) goto LA9; LOC8 = !((*p0).blocks->data[idx0].isloop); LA9: ; if (!LOC8) goto LA7; idx0 -= ((NI) 1); } LA7: ; } { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = (idx0 < ((NI) 0)); if (LOC12) goto LA13; LOC12 = !((*p0).blocks->data[idx0].isloop); LA13: ; if (!LOC12) goto LA14; internalerror_194100_155036129((*t0).info, ((NimStringDesc*) &T839829468_609)); } LA14: ; } LA1: ; label0 = assignlabel_542020_839829468((&(*p0).blocks->data[idx0])); blockleaveactions_543442_839829468(p0, (NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) ((*p0).blocks->data[idx0].nestedtrystmts))), (NI)((*p0).inexceptblock - ((NI) ((*p0).blocks->data[idx0].nestedexceptstmts)))); genlinedir_530823_839829468(p0, t0); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = label0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_556), LOC16, 1); } N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_547080_839829468)(Tcproc527021* p0, Tnode290802* asgn0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { Tnode290802* le0; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 2))&31U)))!=0)) goto LA3; le0 = (*asgn0).kindU.S6.sons->data[((NI) 0)]; { Tsym290834* field0; if (!((*le0).kind == ((Tnodekind290020) 46))) goto LA7; field0 = (*(*(*le0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag290184) 18))&31U)))!=0); } goto LA5; LA7: ; { Tsym290834* field0; if (!((*le0).kind == ((Tnodekind290020) 45))) goto LA10; field0 = (*(*le0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag290184) 18))&31U)))!=0); } goto LA5; LA10: ; LA5: ; } LA3: ; return result0; } N_NIMCALL(Ropeobj177006*, discriminatortabledecl_534094_839829468)(Tcgen527027* m0, Ttype290840* objtype0, Tsym290834* d0) { Ropeobj177006* result0; Ropeobj177006* LOC1; Ropeobj177006* tmp0; TY530811 LOC2; NI64 LOC3; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_130)); tmp0 = discriminatortablename_534057_839829468(m0, objtype0, d0); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = tmp0; LOC3 = (NI64)0; LOC3 = lengthord_318007_3876443242((*d0).typ); LOC2[1] = rope_177401_2381377266((NI64)(LOC3 + IL64(1))); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_203), LOC2, 2); return result0; } N_NIMCALL(void, gendiscriminantcheck_547144_839829468)(Tcproc527021* p0, Tloc290816* a0, Tloc290816* tmp0, Ttype290840* objtype0, Tsym290834* field0) { Ttype290840* t0; Ropeobj177006* LOC1; NI64 L0; TY533235 LOC8; t0 = skiptypes_294099_850551059(objtype0, IL64(211106240964864)); LOC1 = (Ropeobj177006*)0; LOC1 = gentypeinfo_533941_839829468((*p0).module, t0); L0 = lengthord_318007_3876443242((*field0).typ); { NIM_BOOL LOC4; TY177507 LOC7; LOC4 = (NIM_BOOL)0; LOC4 = containsorincl_266862_2627731572((&(*(*p0).module).declaredthings), (*field0).Sup.id); if (!!(LOC4)) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = discriminatortabledecl_534094_839829468((*p0).module, t0, field0); appcg_530640_839829468((*p0).module, ((Tcfilesection527005) 9), ((NimStringDesc*) &T839829468_610), LOC7, 1); } LA5: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_536188_839829468(a0); LOC8[1] = rdloc_536188_839829468(tmp0); LOC8[2] = discriminatortablename_534057_839829468((*p0).module, t0, field0); LOC8[3] = intliteral_537270_839829468((NI64)(L0 + IL64(1))); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_611), LOC8, 4); } N_NIMCALL(void, asgnfielddiscriminant_547209_839829468)(Tcproc527021* p0, Tnode290802* e0) { Tloc290816 a0; Tloc290816 tmp0; Tnode290802* dotexpr0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); dotexpr0 = (*e0).kindU.S6.sons->data[((NI) 0)]; { if (!((*dotexpr0).kind == ((Tnodekind290020) 46))) goto LA3; dotexpr0 = (*dotexpr0).kindU.S6.sons->data[((NI) 0)]; } LA3: ; initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); gettemp_535032_839829468(p0, a0.t, (&tmp0), NIM_FALSE); expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); gendiscriminantcheck_547144_839829468(p0, (&a0), (&tmp0), (*(*dotexpr0).kindU.S6.sons->data[((NI) 0)]).typ, (*(*dotexpr0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym); genassignment_537264_839829468(p0, (&a0), (&tmp0), 0); } N_NIMCALL(void, genasgn_547239_839829468)(Tcproc527021* p0, Tnode290802* e0, NIM_BOOL fastasgn0) { genlinedir_530823_839829468(p0, e0); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)); if (!(LOC3)) goto LA4; LOC3 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 30))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; gengotovar_542258_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)]); } goto LA1; LA5: ; { NIM_BOOL LOC8; Tloc290816 a0; LOC8 = (NIM_BOOL)0; LOC8 = fielddiscriminantcheckneeded_547080_839829468(p0, e0); if (!!(LOC8)) goto LA9; memset((void*)(&a0), 0, sizeof(a0)); { Tnode290802* LOC13; Tnode290802* LOC16; LOC13 = (Tnode290802*)0; LOC13 = HEX5BHEX5D_291238_850551059(e0, ((NI) 0)); if (!((*LOC13).kind == ((Tnodekind290020) 47) || (*LOC13).kind == ((Tnodekind290020) 65))) goto LA14; LOC16 = (Tnode290802*)0; LOC16 = HEX5BHEX5D_291238_850551059(e0, ((NI) 0)); genderef_541921_839829468(p0, LOC16, (&a0), NIM_TRUE); } goto LA11; LA14: ; { initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA11: ; { if (!fastasgn0) goto LA20; a0.flags |= ((NU16)1)<<((((Tlocflag290810) 2))%(sizeof(NU16)*8)); } LA20: ; loadinto_541928_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); } goto LA1; LA9: ; { asgnfielddiscriminant_547209_839829468(p0, e0); } LA1: ; } N_NIMCALL(Ropeobj177006*, genasmoremitstmt_546529_839829468)(Tcproc527021* p0, Tnode290802* t0, NIM_BOOL isasmstmt0) { Ropeobj177006* result0; NimStringDesc* res0; result0 = (Ropeobj177006*)0; res0 = copyString(((NimStringDesc*) &T839829468_490)); { NI i_546547_839829468; NI HEX3Atmp_546644_839829468; NI LOC2; NI res_546647_839829468; i_546547_839829468 = (NI)0; HEX3Atmp_546644_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(t0); HEX3Atmp_546644_839829468 = (NI)(LOC2 - ((NI) 1)); res_546647_839829468 = ((NI) 0); { while (1) { if (!(res_546647_839829468 <= HEX3Atmp_546644_839829468)) goto LA4; i_546547_839829468 = res_546647_839829468; switch ((*(*t0).kindU.S6.sons->data[i_546547_839829468]).kind) { case ((Tnodekind290020) 20) ... ((Tnodekind290020) 22): { res0 = resizeString(res0, (*(*t0).kindU.S6.sons->data[i_546547_839829468]).kindU.S3.strval->Sup.len + 0); appendString(res0, (*(*t0).kindU.S6.sons->data[i_546547_839829468]).kindU.S3.strval); } break; case ((Tnodekind290020) 3): { Tsym290834* sym0; sym0 = (*(*t0).kindU.S6.sons->data[i_546547_839829468]).kindU.S4.sym; { Tloc290816 a0; Ropeobj177006* LOC11; NimStringDesc* LOC12; if (!((28672 &(1U<<((NU)((*sym0).kind)&31U)))!=0)) goto LA9; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[i_546547_839829468], (&a0)); LOC11 = (Ropeobj177006*)0; LOC11 = rdloc_536188_839829468((&a0)); LOC12 = (NimStringDesc*)0; LOC12 = HEX24_177856_2381377266(LOC11); res0 = resizeString(res0, LOC12->Sup.len + 0); appendString(res0, LOC12); } goto LA7; LA9: ; { Ropeobj177006* LOC16; NimStringDesc* LOC17; if (!((*sym0).kind == ((Tsymkind290435) 7))) goto LA14; LOC16 = (Ropeobj177006*)0; LOC16 = gettypedesc_533673_839829468((*p0).module, (*sym0).typ); LOC17 = (NimStringDesc*)0; LOC17 = HEX24_177856_2381377266(LOC16); res0 = resizeString(res0, LOC17->Sup.len + 0); appendString(res0, LOC17); } goto LA7; LA14: ; { Ropeobj177006* r0; NimStringDesc* LOC23; r0 = (*sym0).loc.r; { if (!(r0 == NIM_NIL)) goto LA21; r0 = manglename_531205_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), r0); } LA21: ; LOC23 = (NimStringDesc*)0; LOC23 = HEX24_177856_2381377266(r0); res0 = resizeString(res0, LOC23->Sup.len + 0); appendString(res0, LOC23); } LA7: ; } break; default: { internalerror_194100_155036129((*(*t0).kindU.S6.sons->data[i_546547_839829468]).info, ((NimStringDesc*) &T839829468_612)); } break; } res_546647_839829468 += ((NI) 1); } LA4: ; } } { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = isasmstmt0; if (!(LOC27)) goto LA28; LOC27 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 5))&7U)))!=0); LA28: ; if (!LOC27) goto LA29; { NimStringDesc* x_546604_839829468; NI first_546656_839829468; NI last_546658_839829468; x_546604_839829468 = (NimStringDesc*)0; first_546656_839829468 = ((NI) 0); last_546658_839829468 = ((NI) 0); { while (1) { NI j0; { while (1) { if (!!((((NU8)(res0->data[last_546658_839829468])) == ((NU8)(0)) || ((NU8)(res0->data[last_546658_839829468])) == ((NU8)(13)) || ((NU8)(res0->data[last_546658_839829468])) == ((NU8)(10))))) goto LA35; last_546658_839829468 += ((NI) 1); } LA35: ; } x_546604_839829468 = copyStrLast(res0, first_546656_839829468, (NI)(last_546658_839829468 - ((NI) 1))); j0 = ((NI) 0); { while (1) { if (!(((NU8)(x_546604_839829468->data[j0])) == ((NU8)(32)) || ((NU8)(x_546604_839829468->data[j0])) == ((NU8)(9)))) goto LA37; j0 += ((NI) 1); } LA37: ; } { if (!(((NU8)(x_546604_839829468->data[j0])) == ((NU8)(34)) || ((NU8)(x_546604_839829468->data[j0])) == ((NU8)(58)))) goto LA40; add_177487_2381377266(&result0, x_546604_839829468); add_177487_2381377266(&result0, tnl_175644_4151366050); } goto LA38; LA40: ; { if (!!(((NU8)(x_546604_839829468->data[j0]) == (NU8)(0)))) goto LA43; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_613)); add_177487_2381377266(&result0, x_546604_839829468); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_614)); } goto LA38; LA43: ; LA38: ; { if (!((NU8)(res0->data[last_546658_839829468]) == (NU8)(10))) goto LA47; last_546658_839829468 += ((NI) 1); } goto LA45; LA47: ; { if (!((NU8)(res0->data[last_546658_839829468]) == (NU8)(13))) goto LA50; last_546658_839829468 += ((NI) 1); { if (!((NU8)(res0->data[last_546658_839829468]) == (NU8)(10))) goto LA54; last_546658_839829468 += ((NI) 1); } LA54: ; } goto LA45; LA50: ; { goto LA32; } LA45: ; first_546656_839829468 = last_546658_839829468; } } LA32: ; } } goto LA25; LA29: ; { res0 = resizeString(res0, tnl_175644_4151366050->Sup.len + 0); appendString(res0, tnl_175644_4151366050); result0 = rope_177277_2381377266(res0); } LA25: ; return result0; } N_NIMCALL(void, genasmstmt_546659_839829468)(Tcproc527021* p0, Tnode290802* t0) { Ropeobj177006* s0; genlinedir_530823_839829468(p0, t0); s0 = genasmoremitstmt_546529_839829468(p0, t0, NIM_TRUE); { TY177507 LOC5; if (!((*p0).prc == NIM_NIL)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = s0; addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 7))- 0], Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field17, LOC5, 1); } goto LA1; LA3: ; { TY177507 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = s0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field17, LOC7, 1); } LA1: ; } static N_INLINE(void, gensimpleblock_542095_839829468)(Tcproc527021* p0, Tnode290802* stmts0) { TY531289 LOC1; NI LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0); genstmts_537244_839829468(p0, stmts0); endblock_542060_839829468(p0); } N_NIMCALL(void, gentrycpp_545866_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) { Ropeobj177006* exc0; TY531289 LOC16; NI LOC17; NI length0; TY177507 LOC18; Ropeobj177006* LOC19; NI i0; NIM_BOOL catchallpresent0; TY531289 LOC78; Tnode290802* LOC79; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_295441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind290808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; genlinedir_530823_839829468(p0, t0); exc0 = gettempname_531598_839829468((*p0).module); { Tsym290834* LOC10; Ropeobj177006* LOC13; LOC10 = (Tsym290834*)0; LOC10 = getcompilerproc_336748_3937434831(((NimStringDesc*) &T839829468_615)); if (!!((LOC10 == NIM_NIL))) goto LA11; LOC13 = (Ropeobj177006*)0; LOC13 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615)); } goto LA8; LA11: ; { Ropeobj177006* LOC15; LOC15 = (Ropeobj177006*)0; LOC15 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616)); } LA8: ; (*p0).nestedtrystmts = (Tnodeseq290796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode290802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0); ++(*p0).nestedtrystmts->Sup.len; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (NI)0; LOC17 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_617), LOC16, 0); expr_537248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0); length0 = sonslen_293351_850551059(t0); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = exc0; LOC19 = (Ropeobj177006*)0; LOC19 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_618), LOC18, 1); endblock_542035_839829468(p0, LOC19); { TY531289 LOC24; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_619), LOC24, 0); } LA22: ; (*p0).inexceptblock += ((NI) 1); i0 = ((NI) 1); catchallpresent0 = NIM_FALSE; { while (1) { NIM_BOOL LOC27; NI blen0; LOC27 = (NIM_BOOL)0; LOC27 = (i0 < length0); if (!(LOC27)) goto LA28; LOC27 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 87)); LA28: ; if (!LOC27) goto LA26; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = ((*d0).k == ((Tlockind290808) 1)); if (!(LOC31)) goto LA32; LOC31 = isemptytype_295441_850551059((*t0).typ); LA32: ; if (!LOC31) goto LA33; (*d0).k = ((Tlockind290808) 0); } LA33: ; blen0 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i0]); { Ropeobj177006** LOC39; TY531289 LOC40; if (!(((NI) 1) < i0)) goto LA37; LOC39 = (Ropeobj177006**)0; LOC39 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); memset((void*)LOC40, 0, sizeof(LOC40)); addf_178205_2381377266(LOC39, ((NimStringDesc*) &T839829468_620), LOC40, 0); } LA37: ; { TY531289 LOC45; NI LOC46; TY531289 LOC47; if (!(blen0 == ((NI) 1))) goto LA43; catchallpresent0 = NIM_TRUE; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (NI)0; LOC46 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0); expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC47, 0, sizeof(LOC47)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC47, 0); endblock_542060_839829468(p0); } goto LA41; LA43: ; { Ropeobj177006* orexpr0; TY177507 LOC57; TY531289 LOC58; NI LOC59; TY531289 LOC60; orexpr0 = NIM_NIL; { NI j_545979_839829468; NI HEX3Atmp_546101_839829468; NI res_546104_839829468; j_545979_839829468 = (NI)0; HEX3Atmp_546101_839829468 = (NI)0; HEX3Atmp_546101_839829468 = (NI)(blen0 - ((NI) 2)); res_546104_839829468 = ((NI) 0); { while (1) { TY530811 LOC56; if (!(res_546104_839829468 <= HEX3Atmp_546101_839829468)) goto LA51; j_545979_839829468 = res_546104_839829468; { if (!!((orexpr0 == NIM_NIL))) goto LA54; add_177487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229)); } LA54: ; memset((void*)LOC56, 0, sizeof(LOC56)); LOC56[0] = exc0; LOC56[1] = gentypeinfo_533941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_545979_839829468]).typ); appcg_530632_839829468((*p0).module, &orexpr0, ((NimStringDesc*) &T839829468_621), LOC56, 2); res_546104_839829468 += ((NI) 1); } LA51: ; } } memset((void*)LOC57, 0, sizeof(LOC57)); LOC57[0] = orexpr0; linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_622), LOC57, 1); memset((void*)LOC58, 0, sizeof(LOC58)); LOC59 = (NI)0; LOC59 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC58, 0); expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0); memset((void*)LOC60, 0, sizeof(LOC60)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC60, 0); endblock_542060_839829468(p0); } LA41: ; i0 += ((NI) 1); } LA26: ; } { TY531289 LOC70; NI LOC71; Tnode290802* finallyblock0; TY531289 LOC76; Ropeobj177006* LOC77; if (!!(catchallpresent0)) goto LA63; { TY531289 LOC69; if (!(((NI) 1) < i0)) goto LA67; memset((void*)LOC69, 0, sizeof(LOC69)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_620), LOC69, 0); } LA67: ; memset((void*)LOC70, 0, sizeof(LOC70)); LOC71 = (NI)0; LOC71 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC70, 0); finallyblock0 = lastson_293364_850551059(t0); { if (!((*finallyblock0).kind == ((Tnodekind290020) 107))) goto LA74; genstmts_537244_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]); } LA74: ; memset((void*)LOC76, 0, sizeof(LOC76)); LOC77 = (Ropeobj177006*)0; LOC77 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_623), LOC76, 0); line_530690_839829468(p0, ((Tcprocsection527011) 2), LOC77); endblock_542060_839829468(p0); } LA63: ; memset((void*)LOC78, 0, sizeof(LOC78)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC78, 0); (*p0).inexceptblock -= ((NI) 1); LOC79 = (Tnode290802*)0; LOC79 = pop_316246_1689653243((&(*p0).nestedtrystmts)); { NIM_BOOL LOC82; LOC82 = (NIM_BOOL)0; LOC82 = (i0 < length0); if (!(LOC82)) goto LA83; LOC82 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 107)); LA83: ; if (!LOC82) goto LA84; gensimpleblock_542095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]); } LA84: ; } N_NIMCALL(void, line_530695_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* r0) { Ropeobj177006** LOC1; Ropeobj177006* LOC2; Ropeobj177006* LOC3; LOC1 = (Ropeobj177006**)0; LOC1 = s_527179_3723162438(p0, s0); LOC2 = (Ropeobj177006*)0; LOC2 = rope_177277_2381377266(r0); LOC3 = (Ropeobj177006*)0; LOC3 = indentline_530656_839829468(p0, LOC2); add_177482_2381377266(LOC1, LOC3); } static N_INLINE(Ropeobj177006*, pop_177530_1689653243)(TY189350** s0) { Ropeobj177006* result0; NI L0; result0 = (Ropeobj177006*)0; L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1)); result0 = (*s0)->data[L0]; (*s0) = (TY189350*) setLengthSeq(&((*s0))->Sup, sizeof(Ropeobj177006*), ((NI) (L0))); return result0; } N_NIMCALL(void, gentry_546114_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) { NIM_BOOL LOC8; Ropeobj177006* safepoint0; TY177507 LOC17; TY177507 LOC18; TY177507 LOC37; NI LOC38; NI length0; TY531289 LOC39; TY531289 LOC40; NI LOC41; TY531289 LOC42; NI i0; Tnode290802* LOC95; TY177507 LOC103; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_295441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind290808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; LOC8 = (NIM_BOOL)0; LOC8 = includestr_147249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_624)); genlinedir_530823_839829468(p0, t0); safepoint0 = gettempname_531598_839829468((*p0).module); { Tsym290834* LOC11; Ropeobj177006* LOC14; LOC11 = (Tsym290834*)0; LOC11 = getcompilerproc_336748_3937434831(((NimStringDesc*) &T839829468_615)); if (!!((LOC11 == NIM_NIL))) goto LA12; LOC14 = (Ropeobj177006*)0; LOC14 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615)); } goto LA9; LA12: ; { Ropeobj177006* LOC16; LOC16 = (Ropeobj177006*)0; LOC16 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616)); } LA9: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_625), LOC17, 1); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_626), LOC18, 1); { NIM_BOOL LOC21; TY177507 LOC24; LOC21 = (NIM_BOOL)0; LOC21 = isdefined_198011_1967573533(((NimStringDesc*) &T839829468_627)); if (!LOC21) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_628), LOC24, 1); } goto LA19; LA22: ; { NIM_BOOL LOC26; TY177507 LOC29; LOC26 = (NIM_BOOL)0; LOC26 = isdefined_198011_1967573533(((NimStringDesc*) &T839829468_629)); if (!LOC26) goto LA27; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_630), LOC29, 1); } goto LA19; LA27: ; { NIM_BOOL LOC31; TY177507 LOC34; LOC31 = (NIM_BOOL)0; LOC31 = isdefined_198011_1967573533(((NimStringDesc*) &T839829468_631)); if (!LOC31) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_632), LOC34, 1); } goto LA19; LA32: ; { TY177507 LOC36; memset((void*)LOC36, 0, sizeof(LOC36)); LOC36[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_628), LOC36, 1); } LA19: ; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = safepoint0; LOC38 = (NI)0; LOC38 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_633), LOC37, 1); length0 = sonslen_293351_850551059(t0); (*p0).nestedtrystmts = (Tnodeseq290796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode290802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0); ++(*p0).nestedtrystmts->Sup.len; expr_537248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC39, 0, sizeof(LOC39)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_605), LOC39, 0); endblock_542060_839829468(p0); memset((void*)LOC40, 0, sizeof(LOC40)); LOC41 = (NI)0; LOC41 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_634), LOC40, 0); memset((void*)LOC42, 0, sizeof(LOC42)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_605), LOC42, 0); { TY531289 LOC47; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA45; memset((void*)LOC47, 0, sizeof(LOC47)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_619), LOC47, 0); } LA45: ; (*p0).inexceptblock += ((NI) 1); i0 = ((NI) 1); { while (1) { NIM_BOOL LOC50; NI blen0; LOC50 = (NIM_BOOL)0; LOC50 = (i0 < length0); if (!(LOC50)) goto LA51; LOC50 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 87)); LA51: ; if (!LOC50) goto LA49; { NIM_BOOL LOC54; LOC54 = (NIM_BOOL)0; LOC54 = ((*d0).k == ((Tlockind290808) 1)); if (!(LOC54)) goto LA55; LOC54 = isemptytype_295441_850551059((*t0).typ); LA55: ; if (!LOC54) goto LA56; (*d0).k = ((Tlockind290808) 0); } LA56: ; blen0 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i0]); { TY531289 LOC67; NI LOC68; TY177507 LOC69; TY531289 LOC70; if (!(blen0 == ((NI) 1))) goto LA60; { TY531289 LOC66; if (!(((NI) 1) < i0)) goto LA64; memset((void*)LOC66, 0, sizeof(LOC66)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_635), LOC66, 0); } LA64: ; memset((void*)LOC67, 0, sizeof(LOC67)); LOC68 = (NI)0; LOC68 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC67, 0); memset((void*)LOC69, 0, sizeof(LOC69)); LOC69[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_636), LOC69, 1); expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC70, 0, sizeof(LOC70)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC70, 0); endblock_542060_839829468(p0); } goto LA58; LA60: ; { Ropeobj177006* orexpr0; TY177507 LOC91; NI LOC92; TY177507 LOC93; TY531289 LOC94; orexpr0 = NIM_NIL; { NI j_546247_839829468; NI HEX3Atmp_546521_839829468; NI res_546524_839829468; j_546247_839829468 = (NI)0; HEX3Atmp_546521_839829468 = (NI)0; HEX3Atmp_546521_839829468 = (NI)(blen0 - ((NI) 2)); res_546524_839829468 = ((NI) 0); { while (1) { NimStringDesc* isobjformat0; TY177507 LOC86; if (!(res_546524_839829468 <= HEX3Atmp_546521_839829468)) goto LA74; j_546247_839829468 = res_546524_839829468; { if (!!((orexpr0 == NIM_NIL))) goto LA77; add_177487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229)); } LA77: ; { NIM_BOOL LOC81; LOC81 = (NIM_BOOL)0; LOC81 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC81) goto LA82; LOC81 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA82: ; if (!!(LOC81)) goto LA83; isobjformat0 = copyString(((NimStringDesc*) &T839829468_637)); } goto LA79; LA83: ; { isobjformat0 = copyString(((NimStringDesc*) &T839829468_638)); } LA79: ; memset((void*)LOC86, 0, sizeof(LOC86)); LOC86[0] = gentypeinfo_533941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_546247_839829468]).typ); appcg_530632_839829468((*p0).module, &orexpr0, isobjformat0, LOC86, 1); res_546524_839829468 += ((NI) 1); } LA74: ; } } { if (!(((NI) 1) < i0)) goto LA89; line_530695_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_620)); } LA89: ; memset((void*)LOC91, 0, sizeof(LOC91)); LOC91[0] = orexpr0; LOC92 = (NI)0; LOC92 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_639), LOC91, 1); memset((void*)LOC93, 0, sizeof(LOC93)); LOC93[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_636), LOC93, 1); expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0); memset((void*)LOC94, 0, sizeof(LOC94)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC94, 0); endblock_542060_839829468(p0); } LA58: ; i0 += ((NI) 1); } LA49: ; } (*p0).inexceptblock -= ((NI) 1); LOC95 = (Tnode290802*)0; LOC95 = pop_316246_1689653243((&(*p0).nestedtrystmts)); endblock_542060_839829468(p0); { NIM_BOOL LOC98; Ropeobj177006* LOC102; LOC98 = (NIM_BOOL)0; LOC98 = (i0 < length0); if (!(LOC98)) goto LA99; LOC98 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 107)); LA99: ; if (!LOC98) goto LA100; (*p0).finallysafepoints = (TY189350*) incrSeqV2(&((*p0).finallysafepoints)->Sup, sizeof(Ropeobj177006*)); asgnRefNoCycle((void**) (&(*p0).finallysafepoints->data[(*p0).finallysafepoints->Sup.len]), safepoint0); ++(*p0).finallysafepoints->Sup.len; gensimpleblock_542095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]); LOC102 = (Ropeobj177006*)0; LOC102 = pop_177530_1689653243((&(*p0).finallysafepoints)); } LA100: ; memset((void*)LOC103, 0, sizeof(LOC103)); LOC103[0] = safepoint0; linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_640), LOC103, 1); } N_NIMCALL(NimStringDesc*, getraisefrmt_544824_839829468)(Tcproc527021* p0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; result0 = copyString(((NimStringDesc*) &T839829468_641)); return result0; } N_NIMCALL(void, genraisestmt_544828_839829468)(Tcproc527021* p0, Tnode290802* t0) { { Tnode290802* finallyblock0; if (!(((NI) 0) < (*p0).inexceptblock)) goto LA3; finallyblock0 = lastson_293364_850551059((*p0).nestedtrystmts->data[(NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) 1))]); { if (!((*finallyblock0).kind == ((Tnodekind290020) 107))) goto LA7; gensimpleblock_542095_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]); } LA7: ; } LA3: ; { Tloc290816 a0; Ropeobj177006* e0; Ttype290840* typ0; NimStringDesc* LOC13; TY530811 LOC14; if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA11; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); e0 = rdloc_536188_839829468((&a0)); typ0 = skiptypes_294099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106247256320)); genlinedir_530823_839829468(p0, t0); LOC13 = (NimStringDesc*)0; LOC13 = getraisefrmt_544824_839829468(p0); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = e0; LOC14[1] = makecstring_189638_155036129((*(*(*typ0).sym).name).s); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), LOC13, LOC14, 2); } goto LA9; LA11: ; { genlinedir_530823_839829468(p0, t0); { NIM_BOOL LOC18; NIM_BOOL LOC19; TY531289 LOC24; Ropeobj177006* LOC25; LOC18 = (NIM_BOOL)0; LOC19 = (NIM_BOOL)0; LOC19 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC19) goto LA20; LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA20: ; LOC18 = LOC19; if (!(LOC18)) goto LA21; LOC18 = !(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 31))&63U)))!=0)); LA21: ; if (!LOC18) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); LOC25 = (Ropeobj177006*)0; LOC25 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_623), LOC24, 0); line_530690_839829468(p0, ((Tcprocsection527011) 2), LOC25); } goto LA16; LA22: ; { TY531289 LOC27; memset((void*)LOC27, 0, sizeof(LOC27)); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_642), LOC27, 0); } LA16: ; } LA9: ; } N_NIMCALL(void, gentypesection_536184_839829468)(Tcgen527027* m0, Tnode290802* n0) { } N_NIMCALL(Tcfilesection527005, determinesection_546819_839829468)(Tnode290802* n0) { Tcfilesection527005 result0; result0 = (Tcfilesection527005)0; result0 = ((Tcfilesection527005) 7); { NIM_BOOL LOC3; NI LOC4; NimStringDesc* sec0; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = len_291081_850551059(n0); LOC3 = (((NI) 1) <= LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind >= ((Tnodekind290020) 20) && (*(*n0).kindU.S6.sons->data[((NI) 0)]).kind <= ((Tnodekind290020) 22)); LA5: ; if (!LOC3) goto LA6; sec0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S3.strval; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_643)); if (!LOC10) goto LA11; result0 = ((Tcfilesection527005) 3); } goto LA8; LA11: ; { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_644)); if (!LOC14) goto LA15; result0 = ((Tcfilesection527005) 9); } goto LA8; LA15: ; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_645)); if (!LOC18) goto LA19; result0 = ((Tcfilesection527005) 1); } goto LA8; LA19: ; LA8: ; } LA6: ; return result0; } N_NIMCALL(void, genemit_546839_839829468)(Tcproc527021* p0, Tnode290802* t0) { Ropeobj177006* s0; s0 = genasmoremitstmt_546529_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], NIM_FALSE); { Tcfilesection527005 section0; Tnode290802* LOC5; if (!((*p0).prc == NIM_NIL)) goto LA3; LOC5 = (Tnode290802*)0; LOC5 = HEX5BHEX5D_291238_850551059(t0, ((NI) 1)); section0 = determinesection_546819_839829468(LOC5); genclinedir_530813_839829468(&(*(*p0).module).s[(section0)- 0], (*t0).info); add_177482_2381377266(&(*(*p0).module).s[(section0)- 0], s0); } goto LA1; LA3: ; { genlinedir_530823_839829468(p0, t0); line_530690_839829468(p0, ((Tcprocsection527011) 2), s0); } LA1: ; } N_NIMCALL(void, genbreakpoint_546862_839829468)(Tcproc527021* p0, Tnode290802* t0) { NimStringDesc* name0; name0 = (NimStringDesc*)0; { TY533238 LOC12; NI LOC13; NimStringDesc* LOC14; if (!(((*p0).options &(1U<<((NU)(((Toption168009) 17))&31U)))!=0)) goto LA3; { if (!((*t0).kind == ((Tnodekind290020) 34))) goto LA7; name0 = nsuNormalize((*(*t0).kindU.S6.sons->data[((NI) 1)]).kindU.S3.strval); } goto LA5; LA7: ; { NimStringDesc* LOC10; NimStringDesc* LOC11; breakpointid_546860_839829468 += ((NI) 1); LOC10 = (NimStringDesc*)0; LOC11 = (NimStringDesc*)0; LOC11 = nimIntToStr(breakpointid_546860_839829468); LOC10 = rawNewString(LOC11->Sup.len + 2); appendString(LOC10, ((NimStringDesc*) &T839829468_646)); appendString(LOC10, LOC11); name0 = LOC10; } LA5: ; genlinedir_530823_839829468(p0, t0); memset((void*)LOC12, 0, sizeof(LOC12)); LOC13 = (NI)0; LOC13 = tolinenumber_190415_155036129((*t0).info); LOC12[0] = rope_177401_2381377266(((NI64) (LOC13))); LOC14 = (NimStringDesc*)0; LOC14 = tofilename_190257_155036129((*t0).info.fileindex); LOC12[1] = makecstring_189638_155036129(LOC14); LOC12[2] = makecstring_189638_155036129(name0); appcg_530632_839829468((*p0).module, &gbreakpoints_546861_839829468, ((NimStringDesc*) &T839829468_647), LOC12, 3); } LA3: ; } N_NIMCALL(void, genwatchpoint_547016_839829468)(Tcproc527021* p0, Tnode290802* n0) { Tloc290816 a0; Ttype290840* typ0; TY533238 LOC5; NimStringDesc* LOC6; { { if (!!((((*p0).options &(1U<<((NU)(((Toption168009) 17))&31U)))!=0))) goto LA3; goto BeforeRet; } LA3: ; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); typ0 = skiptypes_294099_850551059((*(*n0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = addrloc_536204_839829468((&a0)); LOC6 = (NimStringDesc*)0; LOC6 = rendertree_309044_382274130((*n0).kindU.S6.sons->data[((NI) 1)], 0); LOC5[1] = makecstring_189638_155036129(LOC6); LOC5[2] = gentypeinfo_533941_839829468((*p0).module, typ0); linecg_530707_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_648), LOC5, 3); }BeforeRet: ; } N_NIMCALL(void, genpragma_547039_839829468)(Tcproc527021* p_547041_839829468, Tnode290802* n0) { { NI i_547054_839829468; NI HEX3Atmp_547073_839829468; NI LOC2; NI res_547076_839829468; i_547054_839829468 = (NI)0; HEX3Atmp_547073_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_293351_850551059(n0); HEX3Atmp_547073_839829468 = (NI)(LOC2 - ((NI) 1)); res_547076_839829468 = ((NI) 0); { while (1) { Tnode290802* it0; Tspecialword273003 LOC5; if (!(res_547076_839829468 <= HEX3Atmp_547073_839829468)) goto LA4; i_547054_839829468 = res_547076_839829468; it0 = (*n0).kindU.S6.sons->data[i_547054_839829468]; LOC5 = (Tspecialword273003)0; LOC5 = whichpragma_316911_2616423590(it0); switch (LOC5) { case ((Tspecialword273003) 191): { genemit_546839_839829468(p_547041_839829468, it0); } break; case ((Tspecialword273003) 131): { genbreakpoint_546862_839829468(p_547041_839829468, it0); } break; case ((Tspecialword273003) 176): { genwatchpoint_547016_839829468(p_547041_839829468, it0); } break; case ((Tspecialword273003) 183): { Tcproc527021* p0; Ropeobj177006** LOC10; p0 = newproc_527206_3723162438(NIM_NIL, (*p_547041_839829468).module); (*p0).options = ((*p0).options & ~ 98304); genstmts_537244_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)]); LOC10 = (Ropeobj177006**)0; LOC10 = s_527179_3723162438(p0, ((Tcprocsection527011) 2)); asgnRefNoCycle((void**) (&(*(*p0).module).injectstmt), (*LOC10)); } break; default: { } break; } res_547076_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, genparforstmt_544208_839829468)(Tcproc527021* p0, Tnode290802* t0) { NI oldbreakidx_544411_839829468; Tsym290834* forloopvar0; Tloc290816 rangea0; Tloc290816 rangeb0; Tnode290802* call0; TY533235 LOC1; NimStringDesc* LOC2; TY531289 LOC3; (*p0).withinloop += ((NI) 1); genlinedir_530823_839829468(p0, t0); oldbreakidx_544411_839829468 = (*p0).breakidx; forloopvar0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; memset((void*)(&rangea0), 0, sizeof(rangea0)); memset((void*)(&rangeb0), 0, sizeof(rangeb0)); assignlocalvar_536614_839829468(p0, forloopvar0); call0 = (*t0).kindU.S6.sons->data[((NI) 1)]; initlocexpr_537283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 1)], (&rangea0)); initlocexpr_537283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 2)], (&rangeb0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&(*forloopvar0).loc)); LOC1[1] = rdloc_536188_839829468((&rangea0)); LOC1[2] = rdloc_536188_839829468((&rangeb0)); LOC2 = (NimStringDesc*)0; LOC2 = getstr_295230_850551059((*call0).kindU.S6.sons->data[((NI) 3)]); LOC1[3] = rope_177277_2381377266(LOC2); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_649), LOC1, 4); memset((void*)LOC3, 0, sizeof(LOC3)); (*p0).breakidx = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC3, 0); (*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE; genstmts_537244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 2)]); endblock_542060_839829468(p0); (*p0).breakidx = oldbreakidx_544411_839829468; (*p0).withinloop -= ((NI) 1); } N_NIMCALL(void, genstate_542117_839829468)(Tcproc527021* p0, Tnode290802* n0) { NI64 idx0; TY177507 LOC9; { NIM_BOOL LOC3; NI LOC4; NimStringDesc* LOC8; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = len_291081_850551059(n0); LOC3 = (LOC4 == ((NI) 1)); if (!(LOC3)) goto LA5; LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 6)); LA5: ; if (!!(LOC3)) goto LA6; LOC8 = (NimStringDesc*)0; LOC8 = HEX24_194185_1689653243(T839829468_650); internalerror_194113_155036129(LOC8); } LA6: ; idx0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = rope_177401_2381377266(idx0); linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_652), LOC9, 1); } N_NIMCALL(void, gengotostate_542144_839829468)(Tcproc527021* p0, Tnode290802* n0) { Tloc290816 a0; TY177507 LOC1; TY531289 LOC2; TY531289 LOC7; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_536188_839829468((&a0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_603), LOC1, 1); (*p0).beforeretneeded = NIM_TRUE; memset((void*)LOC2, 0, sizeof(LOC2)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_653), LOC2, 0); { NI64 i_542214_839829468; NI64 HEX3Atmp_542223_839829468; NI64 res_542226_839829468; i_542214_839829468 = (NI64)0; HEX3Atmp_542223_839829468 = (NI64)0; HEX3Atmp_542223_839829468 = lastord_318004_3876443242((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ); res_542226_839829468 = IL64(0); { while (1) { TY177507 LOC6; if (!(res_542226_839829468 <= HEX3Atmp_542223_839829468)) goto LA5; i_542214_839829468 = res_542226_839829468; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_177401_2381377266(i_542214_839829468); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_654), LOC6, 1); res_542226_839829468 += ((NI) 1); } LA5: ; } } memset((void*)LOC7, 0, sizeof(LOC7)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC7, 0); } N_NIMCALL(void, genbreakstate_542229_839829468)(Tcproc527021* p0, Tnode290802* n0) { Tloc290816 a0; memset((void*)(&a0), 0, sizeof(a0)); { TY177507 LOC5; if (!((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 155))) goto LA3; initlocexpr_537283_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_536188_839829468((&a0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_655), LOC5, 1); } goto LA1; LA3: ; { TY177507 LOC7; initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_536188_839829468((&a0)); linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_656), LOC7, 1); } LA1: ; } N_NIMCALL(void, expr_537248_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) { switch ((*n0).kind) { case ((Tnodekind290020) 3): { Tsym290834* sym0; sym0 = (*n0).kindU.S4.sym; switch ((*sym0).kind) { case ((Tsymkind290435) 13): { { if (!!(((33554448 & (*sym0).flags) == 0))) goto LA5; fillprocloc_537201_839829468(sym0); genprocprototype_537254_839829468((*p0).module, sym0); } goto LA3; LA5: ; { genproc_530951_839829468((*p0).module, sym0); } LA3: ; putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind290435) 12): case ((Tsymkind290435) 15): case ((Tsymkind290435) 14): { { NimStringDesc* LOC13; if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 23))&31U)))!=0)) goto LA11; LOC13 = (NimStringDesc*)0; LOC13 = rawNewString((*(*sym0).name).s->Sup.len + 48); appendString(LOC13, ((NimStringDesc*) &T839829468_270)); appendString(LOC13, (*(*sym0).name).s); localerror_194085_155036129((*n0).info, LOC13); } LA11: ; genproc_530951_839829468((*p0).module, sym0); { NIM_BOOL LOC16; NimStringDesc* LOC20; LOC16 = (NIM_BOOL)0; LOC16 = ((*sym0).loc.r == NIM_NIL); if (LOC16) goto LA17; LOC16 = ((*sym0).loc.t == NIM_NIL); LA17: ; if (!LOC16) goto LA18; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString((*(*sym0).name).s->Sup.len + 20); appendString(LOC20, ((NimStringDesc*) &T839829468_271)); appendString(LOC20, (*(*sym0).name).s); internalerror_194100_155036129((*n0).info, LOC20); } LA18: ; putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind290435) 10): { { NIM_BOOL LOC24; Ropeobj177006* LOC27; LOC24 = (NIM_BOOL)0; LOC24 = issimpleconst_530311_839829468((*sym0).typ); if (!LOC24) goto LA25; LOC27 = (Ropeobj177006*)0; LOC27 = genliteral_547476_839829468(p0, (*sym0).ast, (*sym0).typ); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC27, ((Tstorageloc290812) 1)); } goto LA22; LA25: ; { gencomplexconst_556249_839829468(p0, sym0, d0); } LA22: ; } break; case ((Tsymkind290435) 19): { Ropeobj177006* LOC30; LOC30 = (Ropeobj177006*)0; LOC30 = rope_177401_2381377266(((NI64) ((*sym0).position))); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC30, ((Tstorageloc290812) 0)); } break; case ((Tsymkind290435) 8): case ((Tsymkind290435) 20): case ((Tsymkind290435) 11): case ((Tsymkind290435) 9): { { if (!!(((4194312 & (*sym0).flags) == 0))) goto LA34; genvarprototype_537236_839829468((*p0).module, sym0); } LA34: ; { NIM_BOOL LOC38; NimStringDesc* LOC42; NimStringDesc* LOC43; LOC38 = (NIM_BOOL)0; LOC38 = ((*sym0).loc.r == NIM_NIL); if (LOC38) goto LA39; LOC38 = ((*sym0).loc.t == NIM_NIL); LA39: ; if (!LOC38) goto LA40; LOC42 = (NimStringDesc*)0; LOC43 = (NimStringDesc*)0; LOC43 = nimIntToStr((*sym0).Sup.id); LOC42 = rawNewString((*(*sym0).name).s->Sup.len + LOC43->Sup.len + 20); appendString(LOC42, ((NimStringDesc*) &T839829468_285)); appendString(LOC42, (*(*sym0).name).s); appendString(LOC42, ((NimStringDesc*) &T839829468_12)); appendString(LOC42, LOC43); internalerror_194100_155036129((*n0).info, LOC42); } LA40: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0)) goto LA46; accessthreadlocalvar_530945_839829468(p0, sym0); { NIM_BOOL LOC50; Ropeobj177006* LOC53; LOC50 = (NIM_BOOL)0; LOC50 = emulatedthreadvars_530949_839829468(); if (!LOC50) goto LA51; LOC53 = (Ropeobj177006*)0; LOC53 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_288), (*sym0).loc.r); putintodest_548468_839829468(p0, d0, (*sym0).loc.t, LOC53, ((Tstorageloc290812) 0)); } goto LA48; LA51: ; { putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } LA48: ; } goto LA44; LA46: ; { putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } LA44: ; } break; case ((Tsymkind290435) 5): { { NIM_BOOL LOC59; NimStringDesc* LOC63; NimStringDesc* LOC64; LOC59 = (NIM_BOOL)0; LOC59 = ((*sym0).loc.r == NIM_NIL); if (LOC59) goto LA60; LOC59 = ((*sym0).loc.t == NIM_NIL); LA60: ; if (!LOC59) goto LA61; LOC63 = (NimStringDesc*)0; LOC64 = (NimStringDesc*)0; LOC64 = nimIntToStr((*sym0).Sup.id); LOC63 = rawNewString((*(*sym0).name).s->Sup.len + LOC64->Sup.len + 21); appendString(LOC63, ((NimStringDesc*) &T839829468_289)); appendString(LOC63, (*(*sym0).name).s); appendString(LOC63, ((NimStringDesc*) &T839829468_12)); appendString(LOC63, LOC64); internalerror_194100_155036129((*n0).info, LOC63); } LA61: ; putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind290435) 3): { { NIM_BOOL LOC68; NimStringDesc* LOC72; NimStringDesc* LOC73; LOC68 = (NIM_BOOL)0; LOC68 = ((*sym0).loc.r == NIM_NIL); if (LOC68) goto LA69; LOC68 = ((*sym0).loc.t == NIM_NIL); LA69: ; if (!LOC68) goto LA70; LOC72 = (NimStringDesc*)0; LOC73 = (NimStringDesc*)0; LOC73 = nimIntToStr((*sym0).Sup.id); LOC72 = rawNewString((*(*sym0).name).s->Sup.len + LOC73->Sup.len + 22); appendString(LOC72, ((NimStringDesc*) &T839829468_290)); appendString(LOC72, (*(*sym0).name).s); appendString(LOC72, ((NimStringDesc*) &T839829468_12)); appendString(LOC72, LOC73); internalerror_194100_155036129((*n0).info, LOC72); } LA70: ; putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } break; default: { NimStringDesc* LOC75; LOC75 = (NimStringDesc*)0; LOC75 = rawNewString(reprEnum((NI)(*sym0).kind, (&NTI290435))->Sup.len + 22); appendString(LOC75, ((NimStringDesc*) &T839829468_291)); appendString(LOC75, reprEnum((NI)(*sym0).kind, (&NTI290435))); appendString(LOC75, ((NimStringDesc*) &T839829468_292)); internalerror_194100_155036129((*n0).info, LOC75); } break; } } break; case ((Tnodekind290020) 23): { { NIM_BOOL LOC79; Ropeobj177006* LOC82; LOC79 = (NIM_BOOL)0; LOC79 = isemptytype_295441_850551059((*n0).typ); if (!!(LOC79)) goto LA80; LOC82 = (Ropeobj177006*)0; LOC82 = genliteral_537273_839829468(p0, n0); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC82, ((Tstorageloc290812) 0)); } LA80: ; } break; case ((Tnodekind290020) 20) ... ((Tnodekind290020) 22): { Ropeobj177006* LOC84; LOC84 = (Ropeobj177006*)0; LOC84 = genliteral_537273_839829468(p0, n0); putdataintodest_548436_839829468(p0, d0, (*n0).typ, LOC84); } break; case ((Tnodekind290020) 6) ... ((Tnodekind290020) 15): case ((Tnodekind290020) 16) ... ((Tnodekind290020) 19): case ((Tnodekind290020) 5): { Ropeobj177006* LOC86; LOC86 = (Ropeobj177006*)0; LOC86 = genliteral_537273_839829468(p0, n0); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC86, ((Tstorageloc290812) 0)); } break; case ((Tnodekind290020) 27): case ((Tnodekind290020) 32): case ((Tnodekind290020) 29): case ((Tnodekind290020) 30): case ((Tnodekind290020) 31): case ((Tnodekind290020) 26): case ((Tnodekind290020) 28): { Tnode290802* op0; genlinedir_530823_839829468(p0, n0); op0 = (*n0).kindU.S6.sons->data[((NI) 0)]; { Tloc290816 a0; if (!(*n0).typ == 0) goto LA90; memset((void*)(&a0), 0, sizeof(a0)); { NIM_BOOL LOC94; LOC94 = (NIM_BOOL)0; LOC94 = ((*op0).kind == ((Tnodekind290020) 3)); if (!(LOC94)) goto LA95; LOC94 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic290524) 0))); LA95: ; if (!LOC94) goto LA96; genmagicexpr_555033_839829468(p0, n0, (&a0), (*(*op0).kindU.S4.sym).magic); } goto LA92; LA96: ; { gencall_541632_839829468(p0, n0, (&a0)); } LA92: ; } goto LA88; LA90: ; { { NIM_BOOL LOC102; LOC102 = (NIM_BOOL)0; LOC102 = ((*op0).kind == ((Tnodekind290020) 3)); if (!(LOC102)) goto LA103; LOC102 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic290524) 0))); LA103: ; if (!LOC102) goto LA104; genmagicexpr_555033_839829468(p0, n0, d0, (*(*op0).kindU.S4.sym).magic); } goto LA100; LA104: ; { gencall_541632_839829468(p0, n0, d0); } LA100: ; } LA88: ; } break; case ((Tnodekind290020) 39): { { NIM_BOOL LOC110; NI LOC112; Ropeobj177006* LOC115; LOC110 = (NIM_BOOL)0; LOC110 = isdeepconstexpr_316566_2616423590(n0); if (!(LOC110)) goto LA111; LOC112 = (NI)0; LOC112 = len_291081_850551059(n0); LOC110 = !((LOC112 == ((NI) 0))); LA111: ; if (!LOC110) goto LA113; LOC115 = (Ropeobj177006*)0; LOC115 = gensetnode_547664_839829468(p0, n0); putintodest_548468_839829468(p0, d0, (*n0).typ, LOC115, ((Tstorageloc290812) 0)); } goto LA108; LA113: ; { gensetconstr_555496_839829468(p0, n0, d0); } LA108: ; } break; case ((Tnodekind290020) 41): { { NIM_BOOL LOC120; NI LOC122; LOC120 = (NIM_BOOL)0; LOC120 = isdeepconstexpr_316566_2616423590(n0); if (!(LOC120)) goto LA121; LOC122 = (NI)0; LOC122 = len_291081_850551059(n0); LOC120 = !((LOC122 == ((NI) 0))); LA121: ; if (!LOC120) goto LA123; exprcomplexconst_556684_839829468(p0, n0, d0); } goto LA118; LA123: ; { Ttype290840* LOC126; LOC126 = (Ttype290840*)0; LOC126 = skiptypes_294099_850551059((*n0).typ, IL64(211106242013440)); if (!((*LOC126).kind == ((Ttypekind290244) 24))) goto LA127; genseqconstr_553004_839829468(p0, n0, d0); } goto LA118; LA127: ; { genarrayconstr_556207_839829468(p0, n0, d0); } LA118: ; } break; case ((Tnodekind290020) 37): { { NIM_BOOL LOC133; NI LOC135; LOC133 = (NIM_BOOL)0; LOC133 = isdeepconstexpr_316566_2616423590(n0); if (!(LOC133)) goto LA134; LOC135 = (NI)0; LOC135 = len_291081_850551059(n0); LOC133 = !((LOC135 == ((NI) 0))); LA134: ; if (!LOC133) goto LA136; exprcomplexconst_556684_839829468(p0, n0, d0); } goto LA131; LA136: ; { gentupleconstr_555618_839829468(p0, n0, d0); } LA131: ; } break; case ((Tnodekind290020) 38): { genobjconstr_552903_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 61): { gencast_554538_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 58): case ((Tnodekind290020) 59): case ((Tnodekind290020) 60): { genconv_554633_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 64): case ((Tnodekind290020) 63): { genaddr_551051_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 42): { genbracketexpr_552277_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 47): case ((Tnodekind290020) 65): { genderef_541921_839829468(p0, n0, d0, NIM_FALSE); } break; case ((Tnodekind290020) 45): { genrecordfield_551448_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 46): { gencheckedrecordfield_552046_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 127): case ((Tnodekind290020) 112): { genblock_544083_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 126): { genstmtlistexpr_556402_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 115): { { NI i_557023_839829468; NI HEX3Atmp_557276_839829468; NI LOC151; NI res_557279_839829468; i_557023_839829468 = (NI)0; HEX3Atmp_557276_839829468 = (NI)0; LOC151 = (NI)0; LOC151 = sonslen_293351_850551059(n0); HEX3Atmp_557276_839829468 = (NI)(LOC151 - ((NI) 1)); res_557279_839829468 = ((NI) 0); { while (1) { if (!(res_557279_839829468 <= HEX3Atmp_557276_839829468)) goto LA153; i_557023_839829468 = res_557279_839829468; genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[i_557023_839829468]); res_557279_839829468 += ((NI) 1); } LA153: ; } } } break; case ((Tnodekind290020) 48): case ((Tnodekind290020) 92): { genif_542982_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 93): { expr_537248_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[((NI) 0)], d0); } break; case ((Tnodekind290020) 66): { downconv_556581_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 67): { upconv_556431_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 68): { genrangechck_554591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_563)); } break; case ((Tnodekind290020) 69): { genrangechck_554591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_564)); } break; case ((Tnodekind290020) 70): { genrangechck_554591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_565)); } break; case ((Tnodekind290020) 71): { convstrtocstr_554643_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 72): { convcstrtostr_554655_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 51): case ((Tnodekind290020) 52): { Tsym290834* sym0; sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; genproc_530951_839829468((*p0).module, sym0); { NIM_BOOL LOC166; NimStringDesc* LOC170; LOC166 = (NIM_BOOL)0; LOC166 = ((*sym0).loc.r == NIM_NIL); if (LOC166) goto LA167; LOC166 = ((*sym0).loc.t == NIM_NIL); LA167: ; if (!LOC166) goto LA168; LOC170 = (NimStringDesc*)0; LOC170 = rawNewString((*(*sym0).name).s->Sup.len + 20); appendString(LOC170, ((NimStringDesc*) &T839829468_271)); appendString(LOC170, (*(*sym0).name).s); internalerror_194100_155036129((*n0).info, LOC170); } LA168: ; putlocintodest_537258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tnodekind290020) 155): { genclosure_555836_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 1): { } break; case ((Tnodekind290020) 96): { genwhilestmt_543985_839829468(p0, n0); } break; case ((Tnodekind290020) 99): case ((Tnodekind290020) 100): { genvarstmt_542854_839829468(p0, n0); } break; case ((Tnodekind290020) 101): { genconststmt_542909_839829468(p0, n0); } break; case ((Tnodekind290020) 94): { internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_594)); } break; case ((Tnodekind290020) 97): { gencase_545827_839829468(p0, n0, d0); } break; case ((Tnodekind290020) 109): { genreturnstmt_543617_839829468(p0, n0); } break; case ((Tnodekind290020) 110): { genbreakstmt_544444_839829468(p0, n0); } break; case ((Tnodekind290020) 73): { { if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag290427) 14))&15U)))!=0))) goto LA183; genasgn_547239_839829468(p0, n0, NIM_FALSE); } LA183: ; } break; case ((Tnodekind290020) 74): { { if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag290427) 14))&15U)))!=0))) goto LA188; genasgn_547239_839829468(p0, n0, !(((*p0).prc == NIM_NIL))); } LA188: ; } break; case ((Tnodekind290020) 114): { { Tloc290816 a0; if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA193; genlinedir_530823_839829468(p0, n0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA193: ; } break; case ((Tnodekind290020) 89): { genasmstmt_546659_839829468(p0, n0); } break; case ((Tnodekind290020) 106): { { NIM_BOOL LOC199; NIM_BOOL LOC200; LOC199 = (NIM_BOOL)0; LOC200 = (NIM_BOOL)0; LOC200 = (gcmd_168132_2607990831 == ((Tcommands168076) 2)); if (LOC200) goto LA201; LOC200 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA201: ; LOC199 = LOC200; if (!(LOC199)) goto LA202; LOC199 = !(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 31))&63U)))!=0)); LA202: ; if (!LOC199) goto LA203; gentrycpp_545866_839829468(p0, n0, d0); } goto LA197; LA203: ; { gentry_546114_839829468(p0, n0, d0); } LA197: ; } break; case ((Tnodekind290020) 108): { genraisestmt_544828_839829468(p0, n0); } break; case ((Tnodekind290020) 98): { gentypesection_536184_839829468((*p0).module, n0); } break; case ((Tnodekind290020) 125): case ((Tnodekind290020) 84): case ((Tnodekind290020) 121): case ((Tnodekind290020) 116): case ((Tnodekind290020) 117): case ((Tnodekind290020) 118): case ((Tnodekind290020) 119): case ((Tnodekind290020) 120): case ((Tnodekind290020) 83): case ((Tnodekind290020) 82): { } break; case ((Tnodekind290020) 90): { genpragma_547039_839829468(p0, n0); } break; case ((Tnodekind290020) 91): { Tnode290802* LOC211; LOC211 = (Tnode290802*)0; LOC211 = lastson_293364_850551059(n0); expr_537248_839829468(p0, LOC211, d0); } break; case ((Tnodekind290020) 79): case ((Tnodekind290020) 80): case ((Tnodekind290020) 81): { { Tsym290834* prc0; if (!((*(*n0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1))) goto LA215; prc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NIM_BOOL LOC219; Tsym290834* LOC220; LOC219 = (NIM_BOOL)0; LOC220 = (Tsym290834*)0; LOC220 = skipgenericowner_295280_850551059(prc0); LOC219 = ((*LOC220).kind == ((Tsymkind290435) 6)); if (!(LOC219)) goto LA221; LOC219 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 23))&31U)))!=0)); LA221: ; if (!LOC219) goto LA222; { NIM_BOOL LOC226; NIM_BOOL LOC227; NIM_BOOL LOC228; NIM_BOOL LOC229; Tsym290834* LOC231; NIM_BOOL LOC234; LOC226 = (NIM_BOOL)0; LOC227 = (NIM_BOOL)0; LOC228 = (NIM_BOOL)0; LOC229 = (NIM_BOOL)0; LOC229 = !(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 2))&63U)))!=0)); if (!(LOC229)) goto LA230; LOC231 = (Tsym290834*)0; LOC231 = getmodule_297123_2984716966(prc0); LOC229 = !((((*LOC231).flags &(1U<<((NU)(((Tsymflag290184) 25))&31U)))!=0)); LA230: ; LOC228 = LOC229; if (LOC228) goto LA232; LOC228 = ((65600 & (*prc0).flags) == 64); LA232: ; LOC227 = LOC228; if (LOC227) goto LA233; LOC234 = (NIM_BOOL)0; LOC234 = (((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 6))&31U)))!=0); if (!(LOC234)) goto LA235; LOC234 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 5))&15U)))!=0); LA235: ; LOC227 = LOC234; LA233: ; LOC226 = LOC227; if (LOC226) goto LA236; LOC226 = ((*prc0).kind == ((Tsymkind290435) 13)); LA236: ; if (!LOC226) goto LA237; { NIM_BOOL LOC241; Tnode290802* LOC242; LOC241 = (NIM_BOOL)0; LOC242 = (Tnode290802*)0; LOC242 = getbody_333226_1724185294(prc0); LOC241 = !(((*LOC242).kind == ((Tnodekind290020) 1))); if (LOC241) goto LA243; LOC241 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0); LA243: ; if (!LOC241) goto LA244; genproc_530951_839829468((*p0).module, prc0); } LA244: ; } LA237: ; } LA222: ; } LA215: ; } break; case ((Tnodekind290020) 95): { genparforstmt_544208_839829468(p0, n0); } break; case ((Tnodekind290020) 157): { genstate_542117_839829468(p0, n0); } break; case ((Tnodekind290020) 156): { gengotostate_542144_839829468(p0, n0); } break; case ((Tnodekind290020) 158): { genbreakstate_542229_839829468(p0, n0); } break; default: { NimStringDesc* LOC251; LOC251 = (NimStringDesc*)0; LOC251 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI290020))->Sup.len + 25); appendString(LOC251, ((NimStringDesc*) &T839829468_291)); appendString(LOC251, reprEnum((NI)(*n0).kind, (&NTI290020))); appendString(LOC251, ((NimStringDesc*) &T839829468_657)); internalerror_194100_155036129((*n0).info, LOC251); } break; } } N_NIMCALL(void, genstmts_537244_839829468)(Tcproc527021* p0, Tnode290802* t0) { Tloc290816 a0; memset((void*)(&a0), 0, sizeof(a0)); expr_537248_839829468(p0, t0, (&a0)); { NimStringDesc* LOC5; if (!!(((7 &(1U<<((NU)(a0.k)&15U)))!=0))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_194185_1689653243(T839829468_658); internalerror_194113_155036129(LOC5); } LA3: ; } N_NIMCALL(Tnode290802*, myprocess_561402_839829468)(Tpasscontext339002* b0, Tnode290802* n0) { Tnode290802* result0; Tcgen527027* m0; { result0 = (Tnode290802*)0; result0 = n0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (b0 == NIM_NIL); if (LOC3) goto LA4; LOC3 = skipcodegen_339085_2355241294(n0); LA4: ; if (!LOC3) goto LA5; goto BeforeRet; } LA5: ; m0 = ((Tcgen527027*) (b0)); (*(*m0).initproc).options = initprocoptions_560635_839829468(m0); genstmts_537244_839829468((*m0).initproc, n0); }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj177006*, getsomeinitname_559904_839829468)(Tsym290834* m0, NimStringDesc* suffix0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { NimStringDesc* LOC5; if (!((12288 & (*m0).flags) == 0)) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = mangle_526847_2036603609((*(*(*m0).owner).name).s); result0 = rope_177277_2381377266(LOC5); add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_12)); } LA3: ; add_177487_2381377266(&result0, (*(*m0).name).s); add_177487_2381377266(&result0, suffix0); return result0; } N_NIMCALL(Ropeobj177006*, getinitname_560235_839829468)(Tsym290834* m0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = getsomeinitname_559904_839829468(m0, ((NimStringDesc*) &T839829468_659)); return result0; } N_NIMCALL(Ropeobj177006*, getdatinitname_560239_839829468)(Tsym290834* m0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = getsomeinitname_559904_839829468(m0, ((NimStringDesc*) &T839829468_660)); return result0; } N_NIMCALL(void, registermoduletomain_560243_839829468)(Tsym290834* m0) { Ropeobj177006* init0; Ropeobj177006* datinit0; TY177507 LOC1; TY177507 LOC2; init0 = getinitname_560235_839829468(m0); datinit0 = getdatinitname_560239_839829468(m0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = init0; addf_178205_2381377266(&mainmodprocs_527148_3723162438, ((NimStringDesc*) &T839829468_661), LOC1, 1); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = datinit0; addf_178205_2381377266(&mainmodprocs_527148_3723162438, ((NimStringDesc*) &T839829468_661), LOC2, 1); { TY177507 LOC7; Ropeobj177006* initcall0; TY177507 LOC8; if (!!((((*m0).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0))) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = datinit0; addf_178205_2381377266(&maindatinit_527151_3723162438, ((NimStringDesc*) &T839829468_662), LOC7, 1); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = init0; initcall0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_662), LOC8, 1); { if (!(((*m0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA11; add_177482_2381377266(&mainmodinit_527149_3723162438, initcall0); } goto LA9; LA11: ; { add_177482_2381377266(&othermodsinit_527150_3723162438, initcall0); } LA9: ; } LA5: ; } N_NIMCALL(Ropeobj177006*, genfilenames_559688_839829468)(Tcgen527027* m0) { Ropeobj177006* result0; Ropeobj177006* LOC1; result0 = (Ropeobj177006*)0; LOC1 = (Ropeobj177006*)0; LOC1 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_673)); result0 = NIM_NIL; { NI i_559717_839829468; NI HEX3Atmp_559722_839829468; NI res_559725_839829468; i_559717_839829468 = (NI)0; HEX3Atmp_559722_839829468 = (NI)0; HEX3Atmp_559722_839829468 = ((fileinfos_189629_155036129 ? fileinfos_189629_155036129->Sup.len : 0) - 1); res_559725_839829468 = ((NI) 0); { while (1) { TY177507 LOC5; if (!(res_559725_839829468 <= HEX3Atmp_559722_839829468)) goto LA4; i_559717_839829468 = res_559725_839829468; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = makecstring_189638_155036129(fileinfos_189629_155036129->data[i_559717_839829468].projpath); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_674), LOC5, 1); res_559725_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genmainproc_559729_839829468)(Tcgen527027* m0) { NimStringDesc* nimmain0; NimStringDesc* othermain0; Ropeobj177006* initstackbottomcall0; TY534475 LOC38; TY533238 LOC47; nimmain0 = (NimStringDesc*)0; othermain0 = (NimStringDesc*)0; { NIM_BOOL LOC3; NIM_BOOL LOC12; LOC3 = (NIM_BOOL)0; LOC3 = (targetos_175629_4151366050 == ((Tsystemos175004) 2)); if (!(LOC3)) goto LA4; LOC3 = !(((gglobaloptions_168130_2607990831 & 1280) == 0)); LA4: ; if (!LOC3) goto LA5; { if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 10))&63U)))!=0)) goto LA9; nimmain0 = copyString(((NimStringDesc*) &T839829468_663)); othermain0 = copyString(((NimStringDesc*) &T839829468_664)); } goto LA7; LA9: ; { nimmain0 = copyString(((NimStringDesc*) &T839829468_665)); othermain0 = copyString(((NimStringDesc*) &T839829468_666)); } LA7: ; LOC12 = (NIM_BOOL)0; LOC12 = includestr_147249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_667)); } goto LA1; LA5: ; { if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 8))&63U)))!=0)) goto LA14; nimmain0 = copyString(((NimStringDesc*) &T839829468_665)); othermain0 = copyString(((NimStringDesc*) &T839829468_668)); } goto LA1; LA14: ; { if (!(targetos_175629_4151366050 == ((Tsystemos175004) 24))) goto LA17; nimmain0 = copyString(((NimStringDesc*) &T839829468_669)); othermain0 = copyString(((NimStringDesc*) &T839829468_670)); } goto LA1; LA17: ; { nimmain0 = copyString(((NimStringDesc*) &T839829468_669)); othermain0 = copyString(((NimStringDesc*) &T839829468_671)); } LA1: ; { Ropeobj177006* LOC24; if (!!((gbreakpoints_546861_839829468 == NIM_NIL))) goto LA22; LOC24 = (Ropeobj177006*)0; LOC24 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_672)); } LA22: ; { Ropeobj177006* LOC29; if (!((goptions_168128_2607990831 &(1U<<((NU)(((Toption168009) 17))&31U)))!=0)) goto LA27; LOC29 = (Ropeobj177006*)0; LOC29 = genfilenames_559688_839829468(m0); add_177482_2381377266(&gbreakpoints_546861_839829468, LOC29); } LA27: ; { NIM_BOOL LOC32; LOC32 = (NIM_BOOL)0; LOC32 = (targetos_175629_4151366050 == ((Tsystemos175004) 24)); if (LOC32) goto LA33; LOC32 = (gselectedgc_168133_2607990831 == ((Tgcmode168080) 0)); LA33: ; if (!LOC32) goto LA34; initstackbottomcall0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_490)); } goto LA30; LA34: ; { TY531289 LOC37; memset((void*)LOC37, 0, sizeof(LOC37)); initstackbottomcall0 = ropecg_530407_839829468(m0, ((NimStringDesc*) &T839829468_675), LOC37, 0); } LA30: ; (*m0).labels += ((NI) 1); memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = maindatinit_527151_3723162438; LOC38[1] = gbreakpoints_546861_839829468; LOC38[2] = othermodsinit_527150_3723162438; { NIM_BOOL LOC41; TY531289 LOC45; LOC41 = (NIM_BOOL)0; LOC41 = emulatedthreadvars_530949_839829468(); if (!(LOC41)) goto LA42; LOC41 = !((targetos_175629_4151366050 == ((Tsystemos175004) 24))); LA42: ; if (!LOC41) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC38[3] = ropecg_530407_839829468(m0, ((NimStringDesc*) &T839829468_677), LOC45, 0); } goto LA39; LA43: ; { LOC38[3] = rope_177277_2381377266(((NimStringDesc*) &T839829468_490)); } LA39: ; LOC38[4] = initstackbottomcall0; appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 10))- 0], ((NimStringDesc*) &T839829468_676), LOC38, 5); memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = mainmodinit_527149_3723162438; LOC47[1] = initstackbottomcall0; LOC47[2] = rope_177401_2381377266(((NI64) ((*m0).labels))); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 10))- 0], nimmain0, LOC47, 3); { TY531289 LOC52; if (!!(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 20))&63U)))!=0))) goto LA50; memset((void*)LOC52, 0, sizeof(LOC52)); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 10))- 0], othermain0, LOC52, 0); } LA50: ; } N_NIMCALL(Tnode290802*, myclose_561830_839829468)(Tpasscontext339002* b0, Tnode290802* n0) { Tnode290802* result0; Tcgen527027* m0; { result0 = (Tnode290802*)0; result0 = n0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (b0 == NIM_NIL); if (LOC3) goto LA4; LOC3 = skipcodegen_339085_2355241294(n0); LA4: ; if (!LOC3) goto LA5; goto BeforeRet; } LA5: ; m0 = ((Tcgen527027*) (b0)); { if (!!((n0 == NIM_NIL))) goto LA9; (*(*m0).initproc).options = initprocoptions_560635_839829468(m0); genstmts_537244_839829468((*m0).initproc, n0); } LA9: ; registermoduletomain_560243_839829468((*m0).module); { Tnode290802* disp0; if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA13; (*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 5))%(sizeof(NU8)*8)); disp0 = generatemethoddispatchers_430151_3853300031(); { NI i_561891_839829468; NI HEX3Atmp_561895_839829468; NI LOC16; NI res_561898_839829468; i_561891_839829468 = (NI)0; HEX3Atmp_561895_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_293351_850551059(disp0); HEX3Atmp_561895_839829468 = (NI)(LOC16 - ((NI) 1)); res_561898_839829468 = ((NI) 0); { while (1) { if (!(res_561898_839829468 <= HEX3Atmp_561895_839829468)) goto LA18; i_561891_839829468 = res_561898_839829468; genprocaux_558284_839829468(m0, (*(*disp0).kindU.S6.sons->data[i_561891_839829468]).kindU.S4.sym); res_561898_839829468 += ((NI) 1); } LA18: ; } } genmainproc_559729_839829468(m0); } LA13: ; }BeforeRet: ; return result0; } N_NIMCALL(void, finishmodule_561420_839829468)(Tcgen527027* m0) { NI i0; i0 = ((NI) 0); { while (1) { Tsym290834* prc0; if (!(i0 <= ((*m0).forwardedprocs ? ((*m0).forwardedprocs->Sup.len-1) : -1))) goto LA2; prc0 = (*m0).forwardedprocs->data[i0]; { NimStringDesc* LOC7; if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 4))&31U)))!=0)) goto LA5; LOC7 = (NimStringDesc*)0; LOC7 = rawNewString((*(*prc0).name).s->Sup.len + 17); appendString(LOC7, ((NimStringDesc*) &T839829468_678)); appendString(LOC7, (*(*prc0).name).s); internalerror_194100_155036129((*prc0).info, LOC7); } LA5: ; genprocnoforward_558906_839829468(m0, prc0); i0 += ((NI) 1); } LA2: ; } gforwardedprocscounter_527171_3723162438 -= i0; (*m0).forwardedprocs = (Tsymseq290804*) setLengthSeq(&((*m0).forwardedprocs)->Sup, sizeof(Tsym290834*), ((NI) 0)); } N_NIMCALL(void, geninitcode_560286_839829468)(Tcgen527027* m0) { Ropeobj177006* initname0; Ropeobj177006* prc0; TY177507 LOC1; Ropeobj177006* LOC12; Ropeobj177006* LOC13; Ropeobj177006** LOC14; Ropeobj177006** LOC15; Ropeobj177006** LOC16; Ropeobj177006* LOC17; Ropeobj177006* LOC33; Ropeobj177006** LOC34; Ropeobj177006** LOC35; Ropeobj177006** LOC36; Ropeobj177006* LOC37; Ropeobj177006* LOC38; Ropeobj177006** LOC39; Ropeobj177006** LOC40; Ropeobj177006** LOC41; Ropeobj177006* LOC42; Ropeobj177006* LOC50; TY531289 LOC51; TY177507 LOC52; TY531289 LOC58; initname0 = getinitname_560235_839829468((*m0).module); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = initname0; prc0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_679), LOC1, 1); { TY530811 LOC6; if (!(((NI) 0) < (*m0).typenodes)) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = (*m0).typenodesname; LOC6[1] = rope_177401_2381377266(((NI64) ((*m0).typenodes))); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_680), LOC6, 2); } LA4: ; { TY530811 LOC11; if (!(((NI) 0) < (*m0).nimtypes)) goto LA9; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = (*m0).nimtypesname; LOC11[1] = rope_177401_2381377266(((NI64) ((*m0).nimtypes))); appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_681), LOC11, 2); } LA9: ; LOC12 = (Ropeobj177006*)0; LOC12 = initgcframe_536435_839829468((*m0).initproc); add_177482_2381377266(&prc0, LOC12); LOC13 = (Ropeobj177006*)0; LOC13 = gensectionstart_528081_2760143328(((Tcprocsection527011) 0)); add_177482_2381377266(&prc0, LOC13); LOC14 = (Ropeobj177006**)0; LOC14 = s_527179_3723162438((*m0).preinitproc, ((Tcprocsection527011) 0)); add_177482_2381377266(&prc0, (*LOC14)); LOC15 = (Ropeobj177006**)0; LOC15 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 0)); add_177482_2381377266(&prc0, (*LOC15)); LOC16 = (Ropeobj177006**)0; LOC16 = s_527179_3723162438((*m0).postinitproc, ((Tcprocsection527011) 0)); add_177482_2381377266(&prc0, (*LOC16)); LOC17 = (Ropeobj177006*)0; LOC17 = gensectionend_528116_2760143328(((Tcprocsection527011) 0)); add_177482_2381377266(&prc0, LOC17); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0); if (!(LOC20)) goto LA21; LOC20 = !((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 2))&7U)))!=0)); LA21: ; if (!LOC20) goto LA22; (*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 2))%(sizeof(NU8)*8)); { Ropeobj177006* procname0; Ropeobj177006* LOC28; Ropeobj177006* LOC29; if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 0))&7U)))!=0))) goto LA26; procname0 = makecstring_189638_155036129((*(*(*m0).module).name).s); LOC28 = (Ropeobj177006*)0; LOC28 = quotedfilename_194818_155036129((*(*m0).module).info); LOC29 = (Ropeobj177006*)0; LOC29 = initframe_558140_839829468((*m0).initproc, procname0, LOC28); add_177482_2381377266(&prc0, LOC29); } goto LA24; LA26: ; { TY531289 LOC31; Ropeobj177006* LOC32; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj177006*)0; LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_682), LOC31, 0); add_177482_2381377266(&prc0, LOC32); } LA24: ; } LA22: ; LOC33 = (Ropeobj177006*)0; LOC33 = gensectionstart_528081_2760143328(((Tcprocsection527011) 1)); add_177482_2381377266(&prc0, LOC33); LOC34 = (Ropeobj177006**)0; LOC34 = s_527179_3723162438((*m0).preinitproc, ((Tcprocsection527011) 1)); add_177482_2381377266(&prc0, (*LOC34)); LOC35 = (Ropeobj177006**)0; LOC35 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 1)); add_177482_2381377266(&prc0, (*LOC35)); LOC36 = (Ropeobj177006**)0; LOC36 = s_527179_3723162438((*m0).postinitproc, ((Tcprocsection527011) 1)); add_177482_2381377266(&prc0, (*LOC36)); LOC37 = (Ropeobj177006*)0; LOC37 = gensectionend_528116_2760143328(((Tcprocsection527011) 1)); add_177482_2381377266(&prc0, LOC37); LOC38 = (Ropeobj177006*)0; LOC38 = gensectionstart_528081_2760143328(((Tcprocsection527011) 2)); add_177482_2381377266(&prc0, LOC38); LOC39 = (Ropeobj177006**)0; LOC39 = s_527179_3723162438((*m0).preinitproc, ((Tcprocsection527011) 2)); add_177482_2381377266(&prc0, (*LOC39)); LOC40 = (Ropeobj177006**)0; LOC40 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 2)); add_177482_2381377266(&prc0, (*LOC40)); LOC41 = (Ropeobj177006**)0; LOC41 = s_527179_3723162438((*m0).postinitproc, ((Tcprocsection527011) 2)); add_177482_2381377266(&prc0, (*LOC41)); LOC42 = (Ropeobj177006*)0; LOC42 = gensectionend_528116_2760143328(((Tcprocsection527011) 2)); add_177482_2381377266(&prc0, LOC42); { NIM_BOOL LOC45; Ropeobj177006* LOC49; LOC45 = (NIM_BOOL)0; LOC45 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0); if (!(LOC45)) goto LA46; LOC45 = !((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 0))&7U)))!=0)); LA46: ; if (!LOC45) goto LA47; LOC49 = (Ropeobj177006*)0; LOC49 = deinitframe_558150_839829468((*m0).initproc); add_177482_2381377266(&prc0, LOC49); } LA47: ; LOC50 = (Ropeobj177006*)0; LOC50 = deinitgcframe_536441_839829468((*m0).initproc); add_177482_2381377266(&prc0, LOC50); memset((void*)LOC51, 0, sizeof(LOC51)); addf_178205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC51, 0); memset((void*)LOC52, 0, sizeof(LOC52)); LOC52[0] = getdatinitname_560239_839829468((*m0).module); addf_178205_2381377266(&prc0, ((NimStringDesc*) &T839829468_679), LOC52, 1); { Tcfilesection527005 i_560401_839829468; NI res_560482_839829468; i_560401_839829468 = (Tcfilesection527005)0; res_560482_839829468 = ((NI) 12); { while (1) { Ropeobj177006* LOC56; Ropeobj177006* LOC57; if (!(res_560482_839829468 <= ((NI) 16))) goto LA55; i_560401_839829468 = ((Tcfilesection527005) (res_560482_839829468)); LOC56 = (Ropeobj177006*)0; LOC56 = gensectionstart_528015_2760143328(i_560401_839829468); add_177482_2381377266(&prc0, LOC56); add_177482_2381377266(&prc0, (*m0).s[(i_560401_839829468)- 0]); LOC57 = (Ropeobj177006*)0; LOC57 = gensectionend_528050_2760143328(i_560401_839829468); add_177482_2381377266(&prc0, LOC57); res_560482_839829468 += ((NI) 1); } LA55: ; } } memset((void*)LOC58, 0, sizeof(LOC58)); addf_178205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC58, 0); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 11))- 0], prc0); { NIM_CHAR i_560442_839829468; Ropeobj177006* el_560443_839829468; TY527136 HEX3Atmp_560487_839829468; NIM_CHAR i_560490_839829468; i_560442_839829468 = (NIM_CHAR)0; el_560443_839829468 = (Ropeobj177006*)0; memset((void*)HEX3Atmp_560487_839829468, 0, sizeof(HEX3Atmp_560487_839829468)); memcpy((void*)HEX3Atmp_560487_839829468, (NIM_CONST void*)(*m0).extensionloaders, sizeof(HEX3Atmp_560487_839829468)); i_560490_839829468 = 48; { if (!((NU8)(((NIM_CHAR) (((NU8)(i_560490_839829468))))) <= (NU8)(57))) goto LA62; { while (1) { i_560442_839829468 = i_560490_839829468; el_560443_839829468 = HEX3Atmp_560487_839829468[(((NU8)(i_560490_839829468)))- 48]; { Ropeobj177006* ex0; TY530811 LOC70; if (!!((el_560443_839829468 == NIM_NIL))) goto LA68; memset((void*)LOC70, 0, sizeof(LOC70)); LOC70[0] = rope_177401_2381377266(((NI64) ((NI)(((NI) (((NU8)(i_560442_839829468)))) - ((NI) 48))))); LOC70[1] = el_560443_839829468; ex0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_684), LOC70, 2); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 11))- 0], ex0); } LA68: ; { if (!((NU8)(57) <= (NU8)(((NIM_CHAR) (((NU8)(i_560490_839829468))))))) goto LA73; goto LA64; } LA73: ; i_560490_839829468 += ((NI) 1); } } LA64: ; } LA62: ; } } N_NIMCALL(void, finishtypedescriptions_533842_839829468)(Tcgen527027* m0) { NI i0; i0 = ((NI) 0); { while (1) { Ropeobj177006* LOC3; if (!(i0 < ((*m0).typestack ? (*m0).typestack->Sup.len : 0))) goto LA2; LOC3 = (Ropeobj177006*)0; LOC3 = gettypedesc_533673_839829468(m0, (*m0).typestack->data[i0]); i0 += ((NI) 1); } LA2: ; } } N_NIMCALL(Ropeobj177006*, getcopyright_559665_839829468)(NimStringDesc* cfile0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; { TY177507 LOC5; if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 4))&63U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_177277_2381377266(((NimStringDesc*) &T839829468_686)); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_685), LOC5, 1); } goto LA1; LA3: ; { TY534475 LOC7; NimStringDesc* LOC8; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rope_177277_2381377266(((NimStringDesc*) &T839829468_686)); LOC7[1] = rope_177277_2381377266(Os_175068_4151366050[(targetos_175629_4151366050)- 1].Field0); LOC7[2] = rope_177277_2381377266(Cpu_175496_4151366050[(targetcpu_175627_4151366050)- 1].Field0); LOC7[3] = rope_177277_2381377266(Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field0); LOC8 = (NimStringDesc*)0; LOC8 = getcompilecfilecmd_272284_2528170400(cfile0, NIM_FALSE); LOC7[4] = rope_177277_2381377266(LOC8); result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_687), LOC7, 5); } LA1: ; return result0; } static N_INLINE(void, addinttypes_559659_839829468)(Ropeobj177006** result0) { NimStringDesc* LOC1; TY177507 LOC2; LOC1 = (NimStringDesc*)0; LOC1 = rawNewString(tnl_175644_4151366050->Sup.len + 22); appendString(LOC1, ((NimStringDesc*) &T839829468_688)); appendString(LOC1, tnl_175644_4151366050); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rope_177401_2381377266(((NI64) (Cpu_175496_4151366050[(targetcpu_175627_4151366050)- 1].Field1))); addf_178205_2381377266(result0, LOC1, LOC2, 1); } N_NIMCALL(Ropeobj177006*, getfileheader_559683_839829468)(NimStringDesc* cfile0) { Ropeobj177006* result0; result0 = (Ropeobj177006*)0; result0 = getcopyright_559665_839829468(cfile0); addinttypes_559659_839829468(&result0); return result0; } N_NIMCALL(void, generatethreadlocalstorage_536717_839829468)(Tcgen527027* m0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; TY177507 LOC13; LOC3 = (NIM_BOOL)0; LOC3 = !((nimtv_536656_839829468 == NIM_NIL)); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = (((*m0).flags &(1U<<((NU)(((Codegenflag527025) 1))&7U)))!=0); if (LOC5) goto LA6; LOC5 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; { Ttype290840* t_536761_839829468; NI i_536768_839829468; NI L_536770_839829468; t_536761_839829468 = (Ttype290840*)0; i_536768_839829468 = ((NI) 0); L_536770_839829468 = (nimtvdeps_536674_839829468 ? nimtvdeps_536674_839829468->Sup.len : 0); { while (1) { Ropeobj177006* LOC12; if (!(i_536768_839829468 < L_536770_839829468)) goto LA11; t_536761_839829468 = nimtvdeps_536674_839829468->data[i_536768_839829468]; LOC12 = (Ropeobj177006*)0; LOC12 = gettypedesc_533673_839829468(m0, t_536761_839829468); i_536768_839829468 += ((NI) 1); } LA11: ; } } memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = nimtv_536656_839829468; addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 4))- 0], ((NimStringDesc*) &T839829468_689), LOC13, 1); } LA7: ; } N_NIMCALL(void, generateheaders_558104_839829468)(Tcgen527027* m0) { NimStringDesc* LOC1; Tstrentry147009* it0; LOC1 = (NimStringDesc*)0; LOC1 = rawNewString(tnl_175644_4151366050->Sup.len + tnl_175644_4151366050->Sup.len + 20); appendString(LOC1, tnl_175644_4151366050); appendString(LOC1, ((NimStringDesc*) &T839829468_690)); appendString(LOC1, tnl_175644_4151366050); add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], LOC1); it0 = ((Tstrentry147009*) ((*m0).headerfiles.head)); { while (1) { if (!!((it0 == NIM_NIL))) goto LA3; { NimStringDesc* LOC8; NimStringDesc* LOC9; Ropeobj177006* LOC10; if (!((NU8)((*it0).data->data[((NI) 0)]) == (NU8)(35))) goto LA6; LOC8 = (NimStringDesc*)0; LOC9 = (NimStringDesc*)0; LOC9 = nsuReplaceChar((*it0).data, 96, 34); LOC8 = rawNewString(LOC9->Sup.len + tnl_175644_4151366050->Sup.len + 0); appendString(LOC8, LOC9); appendString(LOC8, tnl_175644_4151366050); LOC10 = (Ropeobj177006*)0; LOC10 = rope_177277_2381377266(LOC8); add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], LOC10); } goto LA4; LA6: ; { TY177507 LOC14; if (!!((((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(34)) || ((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(60))))) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_177277_2381377266((*it0).data); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], ((NimStringDesc*) &T839829468_691), LOC14, 1); } goto LA4; LA12: ; { TY177507 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rope_177277_2381377266((*it0).data); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], ((NimStringDesc*) &T839829468_692), LOC16, 1); } LA4: ; it0 = ((Tstrentry147009*) ((*it0).Sup.next)); } LA3: ; } } N_NIMCALL(Ropeobj177006*, genmodule_560491_839829468)(Tcgen527027* m0, NimStringDesc* cfile0) { Ropeobj177006* result0; Ropeobj177006* LOC1; result0 = (Ropeobj177006*)0; result0 = getfileheader_559683_839829468(cfile0); LOC1 = (Ropeobj177006*)0; LOC1 = genmergeinfo_528203_2760143328(m0); add_177482_2381377266(&result0, LOC1); generatethreadlocalstorage_536717_839829468(m0); generateheaders_558104_839829468(m0); { Tcfilesection527005 i_560614_839829468; NI res_560622_839829468; i_560614_839829468 = (Tcfilesection527005)0; res_560622_839829468 = ((NI) 1); { while (1) { Ropeobj177006* LOC5; Ropeobj177006* LOC6; if (!(res_560622_839829468 <= ((NI) 10))) goto LA4; i_560614_839829468 = ((Tcfilesection527005) (res_560622_839829468)); LOC5 = (Ropeobj177006*)0; LOC5 = gensectionstart_528015_2760143328(i_560614_839829468); add_177482_2381377266(&result0, LOC5); add_177482_2381377266(&result0, (*m0).s[(i_560614_839829468)- 0]); LOC6 = (Ropeobj177006*)0; LOC6 = gensectionend_528050_2760143328(i_560614_839829468); add_177482_2381377266(&result0, LOC6); res_560622_839829468 += ((NI) 1); } LA4: ; } } add_177482_2381377266(&result0, (*m0).s[(((Tcfilesection527005) 11))- 0]); return result0; } N_NIMCALL(void, updatecachedmodule_561813_839829468)(Tcgen527027* m0) { NimStringDesc* cfile0; NimStringDesc* cfilenoext0; cfile0 = getcfile_561201_839829468(m0); cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490)); { NIM_BOOL LOC3; Ropeobj177006* code0; LOC3 = (NIM_BOOL)0; LOC3 = mergerequired_528832_2760143328(m0); if (!(LOC3)) goto LA4; LOC3 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)); LA4: ; if (!LOC3) goto LA5; mergefiles_529241_2760143328(cfile0, m0); geninitcode_560286_839829468(m0); finishtypedescriptions_533842_839829468(m0); code0 = genmodule_560491_839829468(m0, cfile0); writerope_177836_2381377266(code0, cfile0, NIM_FALSE); addfiletocompile_271863_2528170400(cfile0); } LA5: ; addfiletolink_271872_2528170400(cfilenoext0); } N_NIMCALL(void, generatethreadvarssize_536771_839829468)(Tcgen527027* m0) { { NimStringDesc* externc0; TY177507 LOC12; if (!!((nimtv_536656_839829468 == NIM_NIL))) goto LA3; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = !((gcmd_168132_2607990831 == ((Tcommands168076) 2))); if (!(LOC7)) goto LA8; LOC7 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; externc0 = copyString(((NimStringDesc*) &T839829468_693)); } goto LA5; LA9: ; { externc0 = copyString(((NimStringDesc*) &T839829468_490)); } LA5: ; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_177277_2381377266(externc0); addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], ((NimStringDesc*) &T839829468_694), LOC12, 1); } LA3: ; } N_NIMCALL(NIM_BOOL, shouldrecompile_561621_839829468)(Ropeobj177006* code0, NimStringDesc* cfile0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; result0 = NIM_TRUE; { NimStringDesc* objfile0; if (!!(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 1))&63U)))!=0))) goto LA3; objfile0 = toobjfile_271859_2528170400(cfile0); { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = writeropeifnotequal_178511_2381377266(code0, cfile0); if (!LOC7) goto LA8; goto BeforeRet; } LA8: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = nosexistsFile(objfile0); if (!(LOC12)) goto LA13; LOC12 = nosfileNewer(objfile0, cfile0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; } LA14: ; } goto LA1; LA3: ; { writerope_177836_2381377266(code0, cfile0, NIM_FALSE); } LA1: ; }BeforeRet: ; return result0; } N_NIMCALL(void, writemodule_561637_839829468)(Tcgen527027* m0, NIM_BOOL pending0) { NimStringDesc* cfile0; NimStringDesc* cfilenoext0; cfile0 = getcfile_561201_839829468(m0); cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490)); { NIM_BOOL LOC3; Ropeobj177006* code0; LOC3 = (NIM_BOOL)0; LOC3 = !((*m0).Sup.fromcache); if (LOC3) goto LA4; LOC3 = ((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 1))&63U)))!=0); LA4: ; if (!LOC3) goto LA5; geninitcode_560286_839829468(m0); finishtypedescriptions_533842_839829468(m0); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA9; add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], mainmodprocs_527148_3723162438); generatethreadvarssize_536771_839829468(m0); } LA9: ; code0 = genmodule_560491_839829468(m0, cfile0); { NIM_BOOL LOC13; LOC13 = (NIM_BOOL)0; LOC13 = shouldrecompile_561621_839829468(code0, cfile0); if (!LOC13) goto LA14; addfiletocompile_271863_2528170400(cfile0); } LA14: ; } goto LA1; LA5: ; { NIM_BOOL LOC17; NIM_BOOL LOC18; Ropeobj177006* code0; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = pending0; if (!(LOC18)) goto LA19; LOC18 = mergerequired_528832_2760143328(m0); LA19: ; LOC17 = LOC18; if (!(LOC17)) goto LA20; LOC17 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)); LA20: ; if (!LOC17) goto LA21; mergefiles_529241_2760143328(cfile0, m0); geninitcode_560286_839829468(m0); finishtypedescriptions_533842_839829468(m0); code0 = genmodule_560491_839829468(m0, cfile0); writerope_177836_2381377266(code0, cfile0, NIM_FALSE); addfiletocompile_271863_2528170400(cfile0); } goto LA1; LA21: ; { NimStringDesc* LOC24; NIM_BOOL LOC25; LOC24 = (NimStringDesc*)0; LOC24 = toobjfile_271859_2528170400(cfilenoext0); LOC25 = (NIM_BOOL)0; LOC25 = nosexistsFile(LOC24); if (!!(LOC25)) goto LA26; addfiletocompile_271863_2528170400(cfile0); } goto LA1; LA26: ; LA1: ; addfiletolink_271872_2528170400(cfilenoext0); } N_NIMCALL(void, writeheader_561149_839829468)(Tcgen527027* m0) { Ropeobj177006* result0; Ropeobj177006* guard0; TY177507 LOC1; TY124315 LOC2; TY177507 LOC3; TY531289 LOC13; TY177507 LOC14; result0 = getcopyright_559665_839829468((*m0).filename); memset((void*)LOC1, 0, sizeof(LOC1)); memset((void*)(&LOC2), 0, sizeof(LOC2)); nossplitFile((*m0).filename, (&LOC2)); LOC1[0] = rope_177277_2381377266(LOC2.Field1); guard0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_695), LOC1, 1); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = guard0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_696), LOC3, 1); addinttypes_559659_839829468(&result0); generateheaders_558104_839829468(m0); generatethreadlocalstorage_536717_839829468(m0); { Tcfilesection527005 i_561171_839829468; NI res_561197_839829468; i_561171_839829468 = (Tcfilesection527005)0; res_561197_839829468 = ((NI) 1); { while (1) { Ropeobj177006* LOC7; Ropeobj177006* LOC8; if (!(res_561197_839829468 <= ((NI) 10))) goto LA6; i_561171_839829468 = ((Tcfilesection527005) (res_561197_839829468)); LOC7 = (Ropeobj177006*)0; LOC7 = gensectionstart_528015_2760143328(i_561171_839829468); add_177482_2381377266(&result0, LOC7); add_177482_2381377266(&result0, (*m0).s[(i_561171_839829468)- 0]); LOC8 = (Ropeobj177006*)0; LOC8 = gensectionend_528050_2760143328(i_561171_839829468); add_177482_2381377266(&result0, LOC8); res_561197_839829468 += ((NI) 1); } LA6: ; } } add_177482_2381377266(&result0, (*m0).s[(((Tcfilesection527005) 11))- 0]); { if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 8))&63U)))!=0)) goto LA11; add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_22)); } LA11: ; memset((void*)LOC13, 0, sizeof(LOC13)); addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_697), LOC13, 0); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = guard0; addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_698), LOC14, 1); writerope_177836_2381377266(result0, (*m0).filename, NIM_FALSE); } N_NIMCALL(void, cgenwritemodules_561902_839829468)(void) { { if (!!((generatedheader_530201_839829468 == NIM_NIL))) goto LA3; finishmodule_561420_839829468(generatedheader_530201_839829468); } LA3: ; { while (1) { if (!(((NI) 0) < gforwardedprocscounter_527171_3723162438)) goto LA6; { Tcgen527027* m_561916_839829468; m_561916_839829468 = (Tcgen527027*)0; { NI i_561935_839829468; NI HEX3Atmp_561937_839829468; NI res_561939_839829468; i_561935_839829468 = (NI)0; HEX3Atmp_561937_839829468 = (NI)0; HEX3Atmp_561937_839829468 = (gmodules_527170_3723162438 ? (gmodules_527170_3723162438->Sup.len-1) : -1); res_561939_839829468 = ((NI) 0); { while (1) { if (!(res_561939_839829468 <= HEX3Atmp_561937_839829468)) goto LA10; i_561935_839829468 = res_561939_839829468; { if (!!((gmodules_527170_3723162438->data[i_561935_839829468] == NIM_NIL))) goto LA13; m_561916_839829468 = gmodules_527170_3723162438->data[i_561935_839829468]; { if (!!((*m_561916_839829468).Sup.fromcache)) goto LA17; finishmodule_561420_839829468(m_561916_839829468); } LA17: ; } LA13: ; res_561939_839829468 += ((NI) 1); } LA10: ; } } } } LA6: ; } { Tcgen527027* m_561917_839829468; m_561917_839829468 = (Tcgen527027*)0; { NI i_561946_839829468; NI HEX3Atmp_561948_839829468; NI res_561950_839829468; i_561946_839829468 = (NI)0; HEX3Atmp_561948_839829468 = (NI)0; HEX3Atmp_561948_839829468 = (gmodules_527170_3723162438 ? (gmodules_527170_3723162438->Sup.len-1) : -1); res_561950_839829468 = ((NI) 0); { while (1) { if (!(res_561950_839829468 <= HEX3Atmp_561948_839829468)) goto LA22; i_561946_839829468 = res_561950_839829468; { if (!!((gmodules_527170_3723162438->data[i_561946_839829468] == NIM_NIL))) goto LA25; m_561917_839829468 = gmodules_527170_3723162438->data[i_561946_839829468]; { if (!(*m_561917_839829468).Sup.fromcache) goto LA29; updatecachedmodule_561813_839829468(m_561917_839829468); } goto LA27; LA29: ; { writemodule_561637_839829468(m_561917_839829468, NIM_TRUE); } LA27: ; } LA25: ; res_561950_839829468 += ((NI) 1); } LA22: ; } } } writemapping_272789_2528170400(gmapping_527152_3723162438); { if (!!((generatedheader_530201_839829468 == NIM_NIL))) goto LA34; writeheader_561149_839829468(generatedheader_530201_839829468); } LA34: ; } N_NIMCALL(void, nullify_560833_839829468)(Ropeobj177006** arr0) { { Tcfilesection527005 i_560848_839829468; NI res_560853_839829468; i_560848_839829468 = (Tcfilesection527005)0; res_560853_839829468 = ((NI) 0); { while (1) { if (!(res_560853_839829468 <= ((NI) 17))) goto LA3; i_560848_839829468 = ((Tcfilesection527005) (res_560853_839829468)); unsureAsgnRef((void**) (&arr0[(i_560848_839829468)- 0]), NIM_NIL); res_560853_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, nullify_560858_839829468)(Ropeobj177006** arr0) { { NIM_CHAR i_561014_839829468; NI res_561019_839829468; i_561014_839829468 = (NIM_CHAR)0; res_561019_839829468 = ((NI) 48); { while (1) { if (!(res_561019_839829468 <= ((NI) 57))) goto LA3; i_561014_839829468 = ((NIM_CHAR) (res_561019_839829468)); unsureAsgnRef((void**) (&arr0[(((NU8)(i_561014_839829468)))- 48]), NIM_NIL); res_561019_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, resetmodule_560763_839829468)(Tcgen527027* m0) { initlinkedlist_147031_3771138726((&(*m0).headerfiles)); initintset_266885_2627731572((&(*m0).declaredprotos)); initidtable_294019_850551059((&(*m0).forwtypecache)); asgnRef((void**) (&(*m0).initproc), newproc_527206_3723162438(NIM_NIL, m0)); (*(*m0).initproc).options = initprocoptions_560635_839829468(m0); asgnRef((void**) (&(*m0).preinitproc), newpreinitproc_560625_839829468(m0)); asgnRef((void**) (&(*m0).postinitproc), newpostinitproc_560630_839829468(m0)); initnodetable_294085_850551059((&(*m0).datacache)); if ((*m0).typestack) nimGCunrefNoCycle((*m0).typestack); (*m0).typestack = (Ttypeseq290836*) newSeqRC1((&NTI290836), 0); if ((*m0).forwardedprocs) nimGCunrefNoCycle((*m0).forwardedprocs); (*m0).forwardedprocs = (Tsymseq290804*) newSeqRC1((&NTI290804), 0); asgnRefNoCycle((void**) (&(*m0).typenodesname), gettempname_531598_839829468(m0)); asgnRefNoCycle((void**) (&(*m0).nimtypesname), gettempname_531598_839829468(m0)); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0)) goto LA3; (*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 0))%(sizeof(NU8)*8)); } goto LA1; LA3: ; { (*m0).flags &= ~(((NU8)1) << ((((Codegenflag527025) 0)) % (sizeof(NU8)*8))); } LA1: ; nullify_560833_839829468((*m0).s); (*m0).typenodes = ((NI) 0); (*m0).nimtypes = ((NI) 0); nullify_560858_839829468((*m0).extensionloaders); (*m0).Sup.fromcache = NIM_TRUE; } N_NIMCALL(void, resetcgenmodules_561024_839829468)(void) { { Tcgen527027* m_561026_839829468; m_561026_839829468 = (Tcgen527027*)0; { NI i_561031_839829468; NI HEX3Atmp_561033_839829468; NI res_561035_839829468; i_561031_839829468 = (NI)0; HEX3Atmp_561033_839829468 = (NI)0; HEX3Atmp_561033_839829468 = (gmodules_527170_3723162438 ? (gmodules_527170_3723162438->Sup.len-1) : -1); res_561035_839829468 = ((NI) 0); { while (1) { if (!(res_561035_839829468 <= HEX3Atmp_561033_839829468)) goto LA4; i_561031_839829468 = res_561035_839829468; { if (!!((gmodules_527170_3723162438->data[i_561031_839829468] == NIM_NIL))) goto LA7; m_561026_839829468 = gmodules_527170_3723162438->data[i_561031_839829468]; resetmodule_560763_839829468(m_561026_839829468); } LA7: ; res_561035_839829468 += ((NI) 1); } LA4: ; } } } } NIM_EXTERNC N_NOINLINE(void, compiler_cgenInit000)(void) { nimRegisterGlobalMarker(T839829468_2); nimRegisterGlobalMarker(T839829468_3); nimRegisterGlobalMarker(T839829468_5); nimRegisterGlobalMarker(T839829468_6); nimRegisterGlobalMarker(T839829468_7); nimRegisterGlobalMarker(T839829468_8); asgnRefNoCycle((void**) (&indent_530655_839829468), rope_177277_2381377266(((NimStringDesc*) &T839829468_4))); if (nimtvdeps_536674_839829468) nimGCunrefNoCycle(nimtvdeps_536674_839829468); nimtvdeps_536674_839829468 = (Ttypeseq290836*) newSeqRC1((&NTI290836), 0); chckNil((void*)(&nimtvdeclared_536675_839829468)); genericReset((void*)(&nimtvdeclared_536675_839829468), (&NTI266030)); initintset_266885_2627731572((&nimtvdeclared_536675_839829468)); breakpointid_546860_839829468 = ((NI) 0); } NIM_EXTERNC N_NOINLINE(void, compiler_cgenDatInit000)(void) { }
l1_normMEX_basic.c
#include "mex.h" #include <omp.h> #include <math.h> #include "emmintrin.h" #include "xmmintrin.h" void mexFunction(int nlhs, mxArray *left[], int nrhs, const mxArray *right[]) { /* Declare variables */ mwSize elem, cmplx, cmplx1, cmplx2, cmplx3; long long i, elem2; const mwSize size[]={1,1}; mxClassID precision, precision1; mxArray *X1, *X2, *T, *Y; double *pX1r, *pX1i, *pX2r, *pX2i, *pYr, *pT, *pSd, Td, Sd; double xr, xi, L1; float *pX1rf, *pX1if, *pX2rf, *pX2if, *pYrf, *pTf, *pSf, Tf, Sf; float xrf, xif, L1f; /* Get number of elements */ elem = mxGetNumberOfElements(right[0]); /* mexPrintf("elem: %i\n",elem);*/ /* Test for complex and obtain data class */ cmplx = mxIsComplex(right[0]); cmplx1 = mxIsComplex(right[1]); cmplx2 = mxIsComplex(right[2]); cmplx3 = mxIsComplex(right[3]); if (cmplx != cmplx1) mexErrMsgTxt("Inputs 0 and 1 have different complexity"); if (cmplx2) mexErrMsgTxt("Input 2 is complex (must be real)"); if (cmplx3) mexErrMsgTxt("Input 3 is complex (must be real)"); /* Obtain and test data class */ precision = mxGetClassID(right[0]); precision1 = mxGetClassID(right[1]); if (precision != precision1) mexErrMsgTxt("Inputs 0 and 1 have different precision"); /* Get pointers to input arrays and create output array */ Y = mxCreateNumericArray(2, size, precision, mxREAL); if (precision == mxDOUBLE_CLASS) { pX1r = mxGetPr(right[0]); pX2r = mxGetPr(right[1]); if (cmplx) { pX1i = mxGetPi(right[0]); pX2i = mxGetPi(right[1]); } pYr = mxGetPr(Y); } else { pX1rf = mxGetData(right[0]); pX2rf = mxGetData(right[1]); if (cmplx) { pX1if = mxGetImagData(right[0]); pX2if = mxGetImagData(right[1]); } pYrf = mxGetData(Y); } /* Get pointer to input scalar */ if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) pT = mxGetData(right[2]); else pTf = mxGetData(right[2]); /* Get pointer to smoothing factor */ if (mxGetClassID(right[3]) == mxDOUBLE_CLASS) pSd = mxGetData(right[3]); else pSf = mxGetData(right[3]); /* Convert scalars to same data type as input arrays */ if (precision == mxDOUBLE_CLASS) { if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) Td = (double)pT[0]; else Td = (double)pTf[0]; if (mxGetClassID(right[3]) == mxDOUBLE_CLASS) Sd = (double)pSd[0]; else Sd = (double)pSf[0]; } else { if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) Tf = (float)pT[0]; else Tf = (float)pTf[0]; if (mxGetClassID(right[3]) == mxDOUBLE_CLASS) Sf = (float)pSd[0]; else Sf = (float)pSf[0]; } /* Set number of threads */ omp_set_num_threads(16); /* Loop through and compute the abs of the combined coefficients then sum */ if (precision == mxDOUBLE_CLASS) { if (cmplx) { #pragma omp parallel for private(i,xr,xi) reduction(+: L1) for (i=0; i<elem; i++) { xr = pX1r[i] + Td*pX2r[i]; xi = pX1i[i] + Td*pX2i[i]; L1 += sqrt(xr*xr + xi*xi + Sd); } } else { #pragma omp parallel for private(i,xr) reduction(+: L1) for (i=0; i<elem; i++) { xr = pX1r[i] + Td*pX2r[i]; L1 += sqrt(xr*xr + Sd); /*L1 += fabs(pX1r[i] + Td*pX2r[i]);*/ } } pYr[0] = L1; } else { if (cmplx) { #pragma omp parallel for private(i,xrf,xif) reduction(+: L1) for (i=0; i<elem; i++) { xrf = pX1rf[i] + Tf*pX2rf[i]; xif = pX1if[i] + Tf*pX2if[i]; L1 += sqrt(xrf*xrf + xif*xif + Sf); } pYrf[0] = L1; } else { #pragma omp parallel for private(i,xrf) reduction(+: L1) for (i=0; i<elem; i++) { xrf = pX1rf[i] + Tf*pX2rf[i]; L1 += sqrt(xrf*xrf + Sf); /*L1 += fabs(pX1rf[i] + Tf*pX2rf[i]);*/ } pYrf[0] = L1; } } /* Return values */ left[0] = Y; }
GB_unop__identity_uint8_int16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint8_int16) // op(A') function: GB (_unop_tran__identity_uint8_int16) // C type: uint8_t // A type: int16_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint8_t z = (uint8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = (uint8_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint8_int16) ( uint8_t *Cx, // Cx and Ax may be aliased const int16_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int16_t aij = Ax [p] ; uint8_t z = (uint8_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int16_t aij = Ax [p] ; uint8_t z = (uint8_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_uint8_int16) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Dory.c
//#define PY_SSIZE_T_CLEAN //#include <Python.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <math.h> #include <unistd.h> #include <sys/types.h> #include <time.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <time.h> #include <pthread.h> ////////////////// #define VREDUCE1 ////////////////// #define VREDUCE2 //#define COMBIDX // Extract hom cycles #define HOM_CYCLES // Store V adaptively to extract homology basis #define ADAPTIVE_V_STORAGE // minimize lengths of birth cycles //#define MINIMIZE_BIRTH_CYCLES #define STORE_LENGTHS_CYCLES //#define ADD_0PERS_CYCLES //#define MINIMIZE_HOM_CYCLES ///////////////////////////////////////////////// // min of max dist. reduction ///////////////////////////////////////////////// #define DISTMAT_MINMAX ///////////////////////////////////////////////// ///////////////////////////////////////////////// ///////////////////////////////////////////////// //#define POINTCLOUD_MINMAX #define RECORD_V_USAGE ///////////////// // SAVING MACROS ///////////////// //#define SAVEV //#define SAVEPD //#define PRINT ///////////////// // DEBUG MACROS ///////////////// //#define DEBUGCOMBIDX //#define VDEBUG //#define DEBUGPIVOTS //#define COH1DEBUG //#define COMB_IDX(a, b)((a) > (b) ? // self->g_edges_comb_idx[(EDGE_ID)((a*(a-1))/2 + b)] : \ // ( (a) < (b) ? self->g_edges_comb_idx[(EDGE_ID)((b*(b-1))/2 + a)] \ // : self->g_n_valid_edges)) // #define COMB_IDX0(a,b) ( a > b ? (EDGE_ID)((a*(a-1))/2 + b) : (EDGE_ID)((b*(b-1))/2 + a) ) #define COMB_IDX(a,b) ( a == b ? self->g_n_valid_edges : self->g_edges_comb_idx[COMB_IDX0(a, b)]) typedef unsigned long long int BIGINT; typedef unsigned int EDGE_ID; typedef unsigned int VERT_ID; typedef double PAR; typedef struct{ VERT_ID verts[2]; PAR length; }F1; typedef struct{ VERT_ID neighbor; EDGE_ID order; }Neighbors; typedef struct{ EDGE_ID key1; EDGE_ID key2; }simplex; typedef struct{ EDGE_ID col_idx; EDGE_ID o_ab; }H0_pivots; typedef struct{ EDGE_ID key2; EDGE_ID col_idx; EDGE_ID bndry; }H1_cohom_pivots; typedef struct{ EDGE_ID key2; EDGE_ID col_idx; simplex bndry; }H2_cohom_pivots; typedef struct{ int a_ptr; int b_ptr; EDGE_ID o_ab; simplex low; }coboundary_H1; typedef struct{ // The simplex simplex triangle; // Note: triangle.key1 is o_ab // Note: triangle.key2 is c VERT_ID a_ptr; VERT_ID b_ptr; VERT_ID c_ptr; // The low of the simplex simplex low; //key1 is 0: ab, 1: ad, 2: bd, 3: cd int vertex; //vertex is -1 should mean empty. But have not been consistent. //low.key1 = n_valid_edges also means empty. }coboundary_H2; typedef struct{ int original; EDGE_ID len; EDGE_ID max_len; int flag_first; int flag_reduce; int flag_red_w_complex; int flag_append_to_complex; int flag_empty; EDGE_ID pivot; simplex triangle; EDGE_ID R_col_idx; EDGE_ID reduce_with_len; EDGE_ID* trivial_boundary; }boundary_H1_ws; typedef struct{ int original; EDGE_ID len; EDGE_ID max_len; int flag_first; int flag_reduce; int flag_red_w_complex; int flag_append_to_complex; int flag_empty; simplex pivot; simplex tetrahedron; EDGE_ID R_col_idx; EDGE_ID reduce_with_len; simplex* trivial_boundary; }boundary_H2_ws; typedef struct{ int original; EDGE_ID cob; EDGE_ID len; EDGE_ID max_len; int flag_red_w_complex; int flag_append_to_complex; int flag_non_empty; EDGE_ID pivot; }boundary_H0_ws; typedef struct{ EDGE_ID max_len; EDGE_ID last; EDGE_ID* o_ab; }edges_list; typedef struct{ EDGE_ID k2; EDGE_ID o_ab; EDGE_ID a_ptr; EDGE_ID b_ptr; int flag_next; }implicit_keys2; typedef struct{ EDGE_ID k1; int flag_empty; implicit_keys2* keys2; EDGE_ID max_len; EDGE_ID last; }implicit_keys1; typedef struct{ EDGE_ID k1_ptr; EDGE_ID k2_ptr; EDGE_ID edge; implicit_keys1* keys1; edges_list v_edges; EDGE_ID max_len; EDGE_ID last; simplex pivot; int flag_first; int flag_red_w_complex; int flag_red_w_trivial; EDGE_ID reduce_w_bndry; EDGE_ID V_col_idx; int flag_append_to_complex; int flag_non_empty; }coboundary_H1_ws; typedef struct{ EDGE_ID max_len; EDGE_ID last; simplex* o_abc; }triangles_list; typedef struct{ EDGE_ID k2; simplex o_abc; VERT_ID a_ptr; VERT_ID b_ptr; VERT_ID c_ptr; int vertex; int flag_next; }coH2_implicit_keys2; typedef struct{ EDGE_ID k1; int flag_empty; coH2_implicit_keys2* keys2; EDGE_ID max_len; EDGE_ID last; }coH2_implicit_keys1; typedef struct{ EDGE_ID k1_ptr; EDGE_ID k2_ptr; simplex triangle; coH2_implicit_keys1* keys1; triangles_list v_triangles; EDGE_ID max_len; EDGE_ID last; simplex pivot; int flag_first; int flag_red_w_complex; int flag_red_w_trivial; simplex reduce_w_bndry; EDGE_ID V_col_idx; int flag_append_to_complex; int flag_non_empty; }coboundary_H2_ws; typedef struct{ EDGE_ID len; EDGE_ID max_len; EDGE_ID* VV; }hom1_birth; typedef struct{ EDGE_ID* RR; int original; EDGE_ID len; EDGE_ID max_len; }R_struct; typedef struct{ EDGE_ID birth_edge; EDGE_ID death_triangle_key1; EDGE_ID R_col_idx; }homH1_pers; typedef struct{ EDGE_ID len; EDGE_ID max_len; simplex* VV; }hom2_birth; typedef struct{ EDGE_ID* RR; int original; EDGE_ID len; EDGE_ID max_len; }R_struct_H2; typedef struct{ simplex birth_simplex; EDGE_ID death_edge; EDGE_ID R_col_idx; }homH2_pers; typedef struct{ // o_ab EDGE_ID key1; // o_cd EDGE_ID key2; EDGE_ID o_ac; EDGE_ID o_ad; EDGE_ID o_bd; EDGE_ID o_bc; }H2_preprocess; typedef struct{ EDGE_ID key2; EDGE_ID col_idx; simplex tetrahedron; }H2_pivots; typedef struct{ EDGE_ID coface; EDGE_ID V_usage; #ifdef RECORD_V_USAGE EDGE_ID V_depth; #endif int V_stored; EDGE_ID V_len; EDGE_ID* VV; }V_H0; typedef struct{ simplex coface; EDGE_ID V_usage; #ifdef RECORD_V_USAGE EDGE_ID V_depth; #endif int V_stored; EDGE_ID V_len; simplex* VV; }V_H1; typedef struct{ EDGE_ID cycid; EDGE_ID Lidx; EDGE_ID V_len; EDGE_ID* VV; //EDGE_ID ops_len; //EDGE_ID* ops; }min_update_V; typedef struct{ EDGE_ID cycid; EDGE_ID Lidx; EDGE_ID V_len; simplex* VV; //EDGE_ID ops_len; //EDGE_ID* ops; }min_update_V_H2; //#ifdef MINIMIZE_BIRTH_CYCLES typedef struct{ EDGE_ID* boundary; EDGE_ID len; EDGE_ID redw; EDGE_ID diff; //EDGE_ID* ops; //EDGE_ID ops_len; PAR perspair[2]; EDGE_ID Lidx; PAR updated_birth; //EDGE_ID* in_cycles; //EDGE_ID in_cycles_len; //EDGE_ID in_cycles_max_len; }cyc_info; typedef struct{ EDGE_ID cyc; int flag; }update_in_cyc; typedef struct{ EDGE_ID cj; EDGE_ID diff; }cyc_in_cyc; typedef struct{ simplex* boundary; EDGE_ID len; EDGE_ID redw; EDGE_ID diff; PAR perspair[2]; EDGE_ID Lidx; PAR updated_birth; }cyc_info_H2; //#endif int compare_neighbors_vertex(Neighbors s1, Neighbors s2){ if (s1.neighbor < s2.neighbor) return -1; else if (s1.neighbor > s2.neighbor) return 1; else return 0; } int compare_neighbors_order(Neighbors s1, Neighbors s2){ if (s1.order < s2.order) return -1; else if (s1.order > s2.order) return 1; else return 0; } // This is for tim sort int compare_simplex(simplex s1, simplex s2){ if (s1.key1 > s2.key1) return 1; if (s1.key1 < s2.key1) return -1; else{ if (s1.key2 > s2.key2) return 1; else if (s1.key2 < s2.key2) return -1; else return 0; } } // This is for tim sort int compare_cob_H1(coboundary_H1 s1, coboundary_H1 s2){ if (s1.o_ab > s2.o_ab) return 1; else if (s1.o_ab < s2.o_ab) return -1; else return 0; } int compare_coboundary_H2(coboundary_H2 s1, coboundary_H2 s2){ if (s1.triangle.key1 < s2.triangle.key1) return -1; else if (s1.triangle.key1 > s2.triangle.key1) return 1; else{ if (s1.triangle.key2 < s2.triangle.key2) return -1; else if (s1.triangle.key2 > s2.triangle.key2) return 1; else return 0; } } int compare_EDGE_ID ( EDGE_ID x, EDGE_ID y){ if (x < y) return -1; else if (x > y) return 1; else return 0; } #define SORT_NAME sorter //#define SORT_TYPE int64_t #define SORT_TYPE Neighbors #define SORT_CMP(x, y) compare_neighbors_vertex((x), (y)) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter2 //#define SORT_TYPE int64_t #define SORT_TYPE Neighbors #define SORT_CMP(x, y) compare_neighbors_order((x), (y)) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort2.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter3 //#define SORT_TYPE int64_t #define SORT_TYPE EDGE_ID #define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort3.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter4 //#define SORT_TYPE int64_t #define SORT_TYPE simplex #define SORT_CMP(x, y) compare_simplex((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort4.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter5 //#define SORT_TYPE int64_t #define SORT_TYPE coboundary_H1 #define SORT_CMP(x, y) compare_cob_H1((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort5.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter6 //#define SORT_TYPE int64_t #define SORT_TYPE coboundary_H2 #define SORT_CMP(x, y) compare_coboundary_H2((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort6.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter7 //#define SORT_TYPE int64_t #define SORT_TYPE implicit_keys2 int compare_implicit_keys2(implicit_keys2 s1, implicit_keys2 s2){ if (s1.k2 < s2.k2) return -1; else if (s1.k2 > s2.k2) return 1; else{ if (s1.o_ab < s2.o_ab) return -1; else if (s1.o_ab > s2.o_ab) return 1; else return 0; } } #define SORT_CMP(x, y) compare_implicit_keys2((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort7.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter8 //#define SORT_TYPE int64_t #define SORT_TYPE EDGE_ID int compare_edges(EDGE_ID s1, EDGE_ID s2){ if (s1 < s2) return -1; else if (s1 > s2) return 1; else return 0; } #define SORT_CMP(x, y) compare_edges((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort8.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter9 //#define SORT_TYPE int64_t #define SORT_TYPE coH2_implicit_keys2 int coH2_compare_implicit_keys2(coH2_implicit_keys2 s1, coH2_implicit_keys2 s2){ if (s1.k2 < s2.k2) return -1; else if (s1.k2 > s2.k2) return 1; else{ if (s1.o_abc.key1 < s2.o_abc.key1) return -1; else if (s1.o_abc.key1 > s2.o_abc.key1) return 1; else{ if (s1.o_abc.key2 < s2.o_abc.key2) return -1; else if (s1.o_abc.key2 > s2.o_abc.key2) return 1; else return 0; } } } #define SORT_CMP(x, y) coH2_compare_implicit_keys2((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort9.h" #undef SORT_NAME #undef SORT_TYPE #undef SORT_CMP #define SORT_NAME sorter10 //#define SORT_TYPE int64_t #define SORT_TYPE H2_preprocess int compare_tetra_key2(H2_preprocess s1, H2_preprocess s2){ if (s1.key2 < s2.key2) return -1; else if (s1.key2 > s2.key2) return 1; else return 0; } #define SORT_CMP(x, y) compare_tetra_key2((x), (y)) //#define SORT_CMP(x, y) compare_EDGE_ID(x, y) /* You can redefine the comparison operator. The default is #define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1)) but the one below is often faster for integer types. */ //#define SORT_CMP(x, y) ((x->key1) < (y->key1) ? -1 : ((x->key1) == (y->key1) ? ((x->key2 < y->key2 ? -1 : ((x->key2) == (y->key2) ? 0: 1))) : 1)) //#define SORT_CMP(x, y,) compare_partial_cob_dec((x), (y)) #include "sort10.h" int compare_implicit(implicit_keys2 s1, coboundary_H1 phi){ if (s1.k2 < phi.low.key2) return 0; else if (s1.k2 > phi.low.key2) return 1; else{ if (s1.o_ab < phi.o_ab) return 0; else return 1; } } int coH2_compare_implicit(coH2_implicit_keys2 s1, coboundary_H2 phi){ if (s1.k2 < phi.low.key2) return 0; else if (s1.k2 > phi.low.key2) return 1; else{ if (s1.o_abc.key1 < phi.triangle.key1) return 0; else if (s1.o_abc.key1 > phi.triangle.key1) return 1; else{ if (s1.o_abc.key2 < phi.triangle.key2) return 0; else return 1; } } } typedef struct{ char* filename; #ifdef SAVEPD char* g_H0_pers_file; char* g_H1_pers_file; char* g_H2_pers_file; #endif #ifdef SAVEV char* g_coH1_V_file; char* g_coH2_V_file; #endif int g_suppress_output; //#ifdef MINIMIZE_BIRTH_CYCLES char* g_minimal_V_H0_file; //char* g_minimal_V_H0_in_cycles_file; //#ifdef STORE_LENGTHS_CYCLES char* g_V_H0_birthcyc_lens_file; char* g_minimal_V_H0_birthcyc_lens_file; char* g_birth_subset_points_file_H0; char* g_V_H1_birthcyc_lens_file; char* g_minimal_V_H1_birthcyc_lens_file; //#endif char* g_minimal_V_H1_file; //#endif #ifdef MINIMIZE_HOM_CYCLES char* g_minimal_V_hom_H1_file; char* g_minimal_V_hom_H2_file; #ifdef STORE_LENGTHS_CYCLES char* g_minimal_V_H1_homcyc_lens; char* g_minimal_V_H2_homcyc_lens; #endif #endif #ifdef RECORD_V_USAGE char* g_V_H0_usage_file; char* g_V_H1_usage_file; #endif //char* g_file_prefix; //const char* g_H1_boundaries; //const char* g_H1_indices; //const char* g_H2_boundaries; char* g_source; char* g_target; int g_cpu_count; int g_dim_lim; int g_compute_cycles; int g_reduce_cyc_lengths; int g_filetype; PAR g_thresh; VERT_ID g_n_vert; EDGE_ID g_n_valid_edges; BIGINT g_n_all_simp; EDGE_ID* g_edges_list; PAR* g_edge_parameter; #ifdef COMBIDX // Combinatorial idx EDGE_ID g_n_edges; EDGE_ID* g_edges_comb_idx; #endif // Neighbor data structures Neighbors** g_Neighbors; Neighbors** g_Neighbors_e; VERT_ID* g_Neigh_len; EDGE_ID g_max_neighbors; // WORKSPACE PARAMETERS int g_workspace_size; int g_ws_pre_alloc; int g_ws_counter; //////////////////////////////////// // Parallel job allocation //////////////////////////////////// int* g_jobs; int g_sleeping_threads; int g_processed_threads; int g_thread_id; int g_delete_threads; pthread_t *g_threads; pthread_mutex_t g_thread_lock; pthread_cond_t g_start_boss; pthread_cond_t g_start_workers; //////////////////////////////////// // H0 Structures //////////////////////////////////// // Pivots for H0 // i is pivot of A[i] EDGE_ID* g_pivots_H0; // STORE R for H0 EDGE_ID* g_R_sparse_H0; EDGE_ID g_R_sparse_ptr_H0; EDGE_ID g_R_sparse_max_H0; // Mapping of R columns to sparse R linear EDGE_ID* g_R_col_indices_H0; EDGE_ID g_R_col_indices_max_H0; EDGE_ID g_R_col_indices_ptr_H0; // Store pivot for H0 EDGE_ID* g_edges_with_pivots_H0; // H0 WORKSPACE STRUCTURES EDGE_ID** g_R_ws_H0; boundary_H0_ws* g_R_ws_H0_info; //////////////////////////////////// // cohomology H1 structures //////////////////////////////////// EDGE_ID g_this_edge; coboundary_H1* g_coH1_all_lows; // V SPARSE EDGE_ID* g_V_sparse_H1; EDGE_ID g_V_sparse_max; EDGE_ID g_V_sparse_ptr; EDGE_ID g_V_sparse_beg_ptr; EDGE_ID g_V_sparse_end_ptr; EDGE_ID* g_V_col_indices; EDGE_ID g_V_col_indices_max; EDGE_ID g_V_col_indices_ptr; // V workspace coboundary_H1_ws* g_V_ws_H1; // PIVOTS OF H1 COHOMOLOGY H1_cohom_pivots** g_H1_cohom_pivots; EDGE_ID* g_H1_cohom_pivots_len; EDGE_ID* g_H1_cohom_pivots_max_len; // Pers pairs EDGE_ID g_H1_pers_pairs_max_len; EDGE_ID g_H1_pers_pairs_len; PAR* g_H1_pers_pairs; //////////////////////////////////// // cohomology H2 structures //////////////////////////////////// simplex* g_V_sparse_H2; // WORKSPACE STRUCTURES int g_cohom_ws_size; coboundary_H2_ws* g_V_ws_H2; // NEW PIVOTS OF H2 COHOMOLOGY H2_cohom_pivots** g_H2_cohom_pivots; EDGE_ID* g_H2_cohom_pivots_len; EDGE_ID* g_H2_cohom_pivots_max_len; // Pers pairs EDGE_ID g_H2_pers_pairs_max_len; EDGE_ID g_H2_pers_pairs_len; PAR* g_H2_pers_pairs; //////////////////////////////////// // Timers //////////////////////////////////// double g_timer_H2_low; double g_timer_H2_next; double g_timer_H2_greater; struct timespec g_start_wall_clock; struct timespec g_finish_wall_clock; double g_timer_process_input; double g_timer_neigh; double g_timer_H0; double g_timer_coH1; double g_timer_coH2; double g_timer_computeH1; double g_timer_computeH2; double g_timer_H1cycles; double g_timer_H2cycles; double g_timer_minimize_H1cycles; double g_timer_minimize_H2cycles; double g_timer_minimize_H1_homcycles; double g_timer_minimize_H2_homcycles; double g_timer_coH2_serial; double g_timer_coH2_parallel; BIGINT g_n_H1_birth_cycles; BIGINT g_n_H2_birth_cycles; BIGINT g_n_H0_stored_V; BIGINT g_n_H1_stored_V; // Temporary int g_p_flag; EDGE_ID g_counter; //////////////////////////////////// // homology H1 structures //////////////////////////////////// char* g_homH1_cycles_file; EDGE_ID g_R_max_len_H1; EDGE_ID g_R_len_H1; EDGE_ID* g_R_H1; EDGE_ID g_R_col_idx_max_len_H1; EDGE_ID* g_R_col_idx_H1; EDGE_ID g_R_col_idx_H1_ptr; EDGE_ID* g_pivots_H1; // EDGE_ID** g_workspace_H1; boundary_H1_ws* g_workspace_H1_info; //////////////////////////////////// // For H1 birth cycles //////////////////////////////////// #ifdef HOM_CYCLES V_H0* g_H0_pivot_of; #endif R_struct g_temp_R_birth_cycles; hom1_birth g_temp_V_primary; EDGE_ID g_homH1_pers_len; EDGE_ID g_homH1_pers_max_len; homH1_pers* g_homH1_pers; EDGE_ID* g_H1_undead; EDGE_ID g_H1_undead_ptr; EDGE_ID g_H1_undead_max; EDGE_ID g_depth; //////////////////////////////////// // homology H2 structures //////////////////////////////////// char* g_homH2_cycles_file; EDGE_ID g_R_max_len_H2; EDGE_ID g_R_len_H2; simplex* g_R_H2; EDGE_ID g_R_col_idx_max_len_H2; EDGE_ID* g_R_col_idx_H2; EDGE_ID g_R_col_idx_H2_ptr; H2_pivots** g_H2_pivots; EDGE_ID* g_H2_pivots_len; EDGE_ID* g_H2_pivots_max_len; simplex** g_workspace_H2; boundary_H2_ws* g_workspace_H2_info; //////////////////////////////////// // For H2 birth cycles //////////////////////////////////// #ifdef HOM_CYCLES V_H1* g_H1_pivot_of; #endif R_struct_H2 g_temp_R_H2_birth_cycles; hom2_birth g_temp_V_H2_primary; // Pers pairs info EDGE_ID g_homH2_pers_len; EDGE_ID g_homH2_pers_max_len; homH2_pers* g_homH2_pers; simplex* g_H2_undead; EDGE_ID g_H2_undead_ptr; EDGE_ID g_H2_undead_max; int g_extract_cycles; #ifdef ADAPTIVE_V_STORAGE EDGE_ID g_cycle_usage_thresh; EDGE_ID g_cycle_depth_thresh; EDGE_ID g_store_V_for_len; EDGE_ID g_store_V_for_max_len; EDGE_ID* g_store_V_for; simplex* g_store_V_voids_for; #endif //#ifdef MINIMIZE_BIRTH_CYCLES EDGE_ID g_global_minimizer; EDGE_ID g_all_V_stored_num; EDGE_ID g_all_V_stored_max_num; cyc_info* g_all_V_H0_stored; //EDGE_ID** g_all_V_H0_stored; cyc_info_H2* g_all_V_H1_stored; EDGE_ID** g_edges_in_cycles; EDGE_ID* g_edges_in_cycles_len; //#endif #ifdef MINIMIZE_HOM_CYCLES cyc_info* g_all_V_hom_H1_stored; EDGE_ID g_all_V_hom_stored_num; // LEGACY EDGE_ID g_all_V_hom_stored_max_num; EDGE_ID* g_all_V_hom_stored_len; EDGE_ID** g_all_V_hom_H1_stored; simplex** g_all_V_hom_H2_stored; #endif int g_new_debug; int g_new_debug2; EDGE_ID g_debug_edge; simplex g_debug_triangle; // Cycle minimization birth threshold //PAR g_cycle_min_birth_thresh; } filtration; int simplex1_check(VERT_ID, VERT_ID, PAR, PAR); int simplex2_check(VERT_ID, VERT_ID, VERT_ID); int simplex3_check(VERT_ID, VERT_ID, VERT_ID, VERT_ID); // MERGE SORT ALGORITHM void mergeSort(PAR* , EDGE_ID* , EDGE_ID , EDGE_ID ) ; void merge(PAR* , EDGE_ID* , EDGE_ID , EDGE_ID , EDGE_ID ) ; // MERGE SORT ALGORITHM 2 void mergeSort_V_H0(EDGE_ID* , EDGE_ID** , EDGE_ID*, EDGE_ID*, EDGE_ID , EDGE_ID ) ; void merge_V_H0(EDGE_ID* , EDGE_ID** , EDGE_ID*, EDGE_ID*, EDGE_ID , EDGE_ID , EDGE_ID ) ; // MERGE SORT ALGORITHM 3 void mergeSort_V_H1(EDGE_ID* , simplex** , EDGE_ID , EDGE_ID ) ; void merge_V_H1(EDGE_ID* , simplex** , EDGE_ID , EDGE_ID , EDGE_ID ) ; // // MERGE SORT ALGORITHM 4 void mergeSort_update_V(min_update_V* , EDGE_ID , EDGE_ID ) ; void merge_update_V(min_update_V* , EDGE_ID , EDGE_ID , EDGE_ID ) ; // MERGE SORT ALGORITHM 5 void mergeSort_update_V_byLidx(min_update_V* , EDGE_ID , EDGE_ID ) ; void merge_update_V_byLidx(min_update_V* , EDGE_ID , EDGE_ID , EDGE_ID ) ; // MERGE SORT ALGORITHM 6: Sort Lcycid, Llen, Lupdated by Llen void mergeSort_Llen(EDGE_ID*, EDGE_ID*, EDGE_ID*, EDGE_ID, EDGE_ID ) ; void merge_Llen(EDGE_ID*, EDGE_ID*, EDGE_ID*, EDGE_ID, EDGE_ID, EDGE_ID ) ; // MERGE SORT ALGORITHM 7: Sort void mergeSort_temp_par(PAR*, EDGE_ID*, EDGE_ID, EDGE_ID ) ; void merge_temp_par(PAR*, EDGE_ID*, EDGE_ID, EDGE_ID, EDGE_ID ) ; // MERGE SORT ALGORITHM 8: Sort void mergeSort_incycleslen(EDGE_ID*, cyc_info*, EDGE_ID, EDGE_ID ) ; void merge_incycleslen(EDGE_ID*, cyc_info*, EDGE_ID, EDGE_ID, EDGE_ID ) ; // MERGE SORT ALGORITHM 9: Sort void mergeSort_edges_in_cycles(EDGE_ID*, cyc_info*, EDGE_ID, EDGE_ID ) ; void merge_edges_in_cycles(EDGE_ID*, cyc_info*, EDGE_ID, EDGE_ID, EDGE_ID ) ; // MERGE SORT ALGORITHM 10: Sort void mergeSort_edges_in_cycles_bycycid(EDGE_ID*, EDGE_ID, EDGE_ID ) ; void merge_edges_in_cycles_bycycid(EDGE_ID*, EDGE_ID, EDGE_ID, EDGE_ID ) ; ////////////////////////////////////////////////////////////// // NEIGHBOR CREATION AND SEARCH ALGORITHMS ////////////////////////////////////////////////////////////// void update_neighbors_new(filtration* , VERT_ID , VERT_ID , EDGE_ID); VERT_ID search_Neighbors(filtration* , VERT_ID , VERT_ID , VERT_ID , VERT_ID); VERT_ID search_Neighbors_e(filtration* , VERT_ID , EDGE_ID , VERT_ID , VERT_ID, EDGE_ID); VERT_ID bin_search_min_geq_Ne(Neighbors* , VERT_ID, VERT_ID, VERT_ID, EDGE_ID); VERT_ID bin_search_min_geq_N(Neighbors* , VERT_ID, VERT_ID, VERT_ID, EDGE_ID); EDGE_ID bin_search_cycle_ops(EDGE_ID*, EDGE_ID, EDGE_ID, EDGE_ID, EDGE_ID); EDGE_ID bin_search_cyc_in_cyc(cyc_in_cyc* , EDGE_ID , EDGE_ID , EDGE_ID , EDGE_ID ); ////////////////////////////////////////////////////////////// // H0 HOMOLOGY FUNCTIONS // Parallel homology reduction H0 //main reduction void reduce_ws_H0(filtration* ); //reduction with complex void* reduce_with_complex_H0(void* ); //reduction with self void reduce_with_self_H0(filtration* ); //Update R void update_R_H0(filtration* , int ); void allocate_jobs(filtration*, int); BIGINT compute_num_simplices(filtration* ); // H1 cohomology functions void update_V_coH1 (filtration*, int); void find_H1_cohom_next (filtration* , coboundary_H1* ); void find_H1_cohom_low(filtration* , coboundary_H1* ); void find_H1_cohom_greater(filtration* , coboundary_H1* , simplex* ); void insert_in_implicit_v(filtration* , int, coboundary_H1*, int); void print_v_implicit(filtration*, int ); void reduce_ws_coH1(filtration* ); void reduce_with_self_coH1(filtration* ); void* reduce_with_complex_coH1(void* ); void reduce_hash_table_coH1(filtration*, int ); void coH2_insert_in_implicit_v(filtration*, int , coboundary_H2* , int ); void reduce_hash_table_coH2(filtration*, int ); void coH2_print_v_implicit(filtration*, int ); void find_H2_cohom_next (filtration* , coboundary_H2* ); void find_H2_cohom_low(filtration* , coboundary_H2* ); void find_H2_cohom_greater(filtration* , coboundary_H2* , simplex* ); int H2_case1 (filtration*, coboundary_H2*); void H2_case2 (filtration*, coboundary_H2*); EDGE_ID search_H1_cohom_pivots(H1_cohom_pivots* , EDGE_ID , EDGE_ID , EDGE_ID , EDGE_ID ); EDGE_ID search_H2_cohom_pivots(H2_cohom_pivots* , EDGE_ID , EDGE_ID , EDGE_ID , EDGE_ID ); void H2_reduce (filtration*, coboundary_H2*, EDGE_ID, int); void update_V_coH2(filtration* , int ); void add_coH2_pivot(filtration*, simplex, simplex, EDGE_ID); void reduce_ws_coH2(filtration* ); void* reduce_with_complex_coH2(void* ); void reduce_with_self_coH2(filtration* ); // H1 HOMOLOGY FUNCTIONS //main reduction void reduce_ws_H1(filtration* ); //reduction with complex void* reduce_with_complex_H1(void* ); //reduction with self void reduce_with_self_H1(filtration* ); //Update R void update_R_H1(filtration* , int ); EDGE_ID bin_search_max_less_V(EDGE_ID* , EDGE_ID , EDGE_ID , EDGE_ID , EDGE_ID ); EDGE_ID bin_search_min_greater_updated_V_byLidx(EDGE_ID* , EDGE_ID , EDGE_ID , EDGE_ID , EDGE_ID ); EDGE_ID find_first_diff_H0(EDGE_ID* \ , EDGE_ID \ , EDGE_ID** ); // H1 cycles void compute_H1_homology_cycles(filtration* ); void get_birth_cycle(filtration*, EDGE_ID); void find_V_recursively_edges(filtration*, EDGE_ID, EDGE_ID); void shuffle_cyc(cyc_info*, EDGE_ID); //#ifdef MINIMIZE_BIRTH_CYCLES void minimize_birth_cycles_H0(filtration*, EDGE_ID**, EDGE_ID*, EDGE_ID, char*); void minimize_birth_cycles_H0_v2(filtration*, EDGE_ID**, EDGE_ID*, EDGE_ID, char*); void minimize_birth_cycles_H1(filtration*); void minimize_birth_cycles_H1_v2(filtration* \ , cyc_info_H2* \ , EDGE_ID \ , char* \ , char* \ , char* \ ); void minimize_birth_cycles_H0_v3(filtration* \ , cyc_info* \ , EDGE_ID \ , char* \ , char* \ , char* \ , char* \ ); void minimize_birth_cycles_H0_v4(filtration* \ , cyc_info* \ , EDGE_ID \ , char* \ , char* \ ); void minimal_CASE1(EDGE_ID , cyc_info* , EDGE_ID* , EDGE_ID*, EDGE_ID ); void minimal_CASE2(filtration*, EDGE_ID , cyc_info* , EDGE_ID* , EDGE_ID* \ , EDGE_ID* , EDGE_ID ); void update_diff(filtration* , EDGE_ID , EDGE_ID* , int \ , EDGE_ID* , cyc_info* , EDGE_ID); void find_first_diff(filtration* , EDGE_ID , EDGE_ID*\ , EDGE_ID* , cyc_info* , EDGE_ID); //#endif void store_V_H0(filtration* ); void reduce_temp_V_H0(filtration* ); // H2 HOMOLOGY FUNCTIONS //main reduction void reduce_ws_H2(filtration* ); //reduction with complex void* reduce_with_complex_H2(void* ); //reduction with self void reduce_with_self_H2(filtration* ); //Update R void update_R_H2(filtration* , int ); //add_pivot void add_H2_pivot (filtration* , simplex , simplex , EDGE_ID ); //search pivot EDGE_ID search_H2_pivots(H2_pivots* , EDGE_ID , EDGE_ID , EDGE_ID , EDGE_ID ); // H2 cycles void compute_boundary_triangle(filtration* , simplex , EDGE_ID* ); void compute_boundary_tetra(filtration* , simplex , simplex* ); void compute_H2_homology_cycles(filtration* ); void get_birth_void(filtration*, simplex); void find_V_recursively_triangles(filtration*, simplex, EDGE_ID); void store_V_H1(filtration* ); void reduce_temp_V_H1(filtration* ); // DEALLOCATE void deallocator(filtration*); int main(int argc, char* argv[]){ //static PyObject *compute_PH(PyObject *self2, PyObject *args){ struct timespec start_wall_clock, finish_wall_clock; clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); // Filetype = 0 : Distance matrix // Filetype = 1 : Locations // Filetype = 2 : Edge list with edge length //printf("%ld", (long)getpid()); filtration* self; self = (filtration*)malloc(sizeof(filtration)); self->g_new_debug = 0; ////////////////////////////////////////////////////// // Set testing timers and test counters ////////////////////////////////////////////////////// self->g_counter = 0; self->g_timer_H2_low = 0; self->g_timer_H2_next = 0; self->g_timer_H2_greater = 0; self->g_timer_coH2_serial = 0; self->g_timer_coH2_parallel = 0; ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// //if (!PyArg_ParseTuple(args, "sdiisiiii"\ // , &(self->g_source), &(self->g_thresh)\ // , &(self->g_filetype), &(self->g_cpu_count)\ // , &(self->g_target), &(self->g_dim_lim)\ // , &(self->g_compute_cycles), &(self->g_reduce_cyc_lengths)\ // , &(self->g_suppress_output)\ // )){ // printf("\nERROR in parse args"); // return NULL; // //, &(self->g_cycle_min_birth_thresh)\ //} //int file_len = strlen(self->g_target) + 100; int file_len = strlen(argv[5]) + 100; self->g_thresh = atof(argv[2]); self->g_filetype = atoi(argv[3]); self->g_cpu_count = atoi(argv[4]); self->g_dim_lim = atoi(argv[6]); self->g_compute_cycles = atoi(argv[7]); self->g_reduce_cyc_lengths = atoi(argv[8]); self->g_suppress_output = atoi(argv[9]); char* duplicate = (char*)malloc(file_len*sizeof(char)); //strcpy(duplicate, self->g_target); strcpy(duplicate, argv[1]); self->filename = strdup(duplicate); strcpy(duplicate, argv[5]); self->g_target = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "homH1_cycles.txt"); self->g_homH1_cycles_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "homH2_cycles.txt"); self->g_homH2_cycles_file = strdup(duplicate); //#ifdef MINIMIZE_BIRTH_CYCLES strcpy(duplicate, self->g_target); strcat(duplicate, "minimal_V_birth_H1.txt"); self->g_minimal_V_H0_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "birth_subsets_H1.txt"); self->g_birth_subset_points_file_H0 = strdup(duplicate); //strcpy(duplicate, argv[5]); //strcat(duplicate, "minimal_V_birth_H1_in_cycles.txt"); //self->g_minimal_V_H0_in_cycles_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "minimal_V_birth_H2.txt"); self->g_minimal_V_H1_file = strdup(duplicate); //#ifdef STORE_LENGTHS_CYCLES strcpy(duplicate, self->g_target); strcat(duplicate, "V_birth_len_H1.txt"); self->g_V_H0_birthcyc_lens_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "minimal_V_birth_len_H1.txt"); self->g_minimal_V_H0_birthcyc_lens_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "V_birth_len_H2.txt"); self->g_V_H1_birthcyc_lens_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "minimal_V_birth_len_H2.txt"); self->g_minimal_V_H1_birthcyc_lens_file = strdup(duplicate); //#endif //#endif #ifdef MINIMIZE_HOM_CYCLES if (self->g_reduce_cyc_lengths){ strcpy(duplicate, self->g_target); strcat(duplicate, "minimal_V_hom_H1.txt"); self->g_minimal_V_hom_H1_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "minimal_V_hom_H2.txt"); self->g_minimal_V_hom_H2_file = strdup(duplicate); } #endif #ifdef RECORD_V_USAGE strcpy(duplicate, self->g_target); strcat(duplicate, "V_H0_usage.txt"); self->g_V_H0_usage_file = strdup(duplicate); strcpy(duplicate, self->g_target); strcat(duplicate, "V_H1_usage.txt"); self->g_V_H1_usage_file = strdup(duplicate); #endif #if defined(SAVEPD) || defined(SAVEV) strcpy(duplicate, self->g_target); strcat(duplicate, "H0_pers_data.txt"); self->g_H0_pers_file = strdup(duplicate); if (self->g_dim_lim > 0){ strcpy(duplicate, self->g_target); strcat(duplicate, "H1_pers_data.txt"); self->g_H1_pers_file = strdup(duplicate); #ifdef SAVEV strcpy(duplicate, self->g_target); strcat(duplicate, "coH1_V_data.txt"); self->g_coH1_V_file = strdup(duplicate); #endif if (self->g_dim_lim > 1){ strcpy(duplicate, self->g_target); strcat(duplicate, "H2_pers_data.txt"); self->g_H2_pers_file = strdup(duplicate); #ifdef SAVEV strcpy(duplicate, self->g_target); strcat(duplicate, "coH2_V_data.txt"); self->g_coH2_V_file = strdup(duplicate); #endif } } #endif free(duplicate); //self->g_extract_cycles = atoi(argv[6]); //self->g_cycle_birth_limit = atof(argv[7]); #ifdef ADAPTIVE_V_STORAGE self->g_cycle_usage_thresh = 2; self->g_cycle_depth_thresh = 1; #endif omp_set_num_threads(self->g_cpu_count); FILE *fp = fopen(self->filename, "r"); if (fp == NULL){ perror("Unable to open file!"); exit(1); } char* line = NULL; size_t len = 0; char* dist; PAR dist_d; char* end; getline(&line, &len, fp); dist = strtok(line, " ,"); fclose(fp); fp = fopen(self->filename, "r"); int prealloc = 100000; VERT_ID row = 0; VERT_ID col = 0; self->g_edges_list = (EDGE_ID*)malloc(2*prealloc*sizeof(EDGE_ID)); self->g_edge_parameter = (PAR*)malloc(prealloc*sizeof(PAR)); self->g_n_valid_edges = 0; if (self->g_filetype == 0){ #ifdef DISTMAT_MINMAX PAR dist_min_max, dist_max; dist_min_max = INFINITY; // this is a distance matrix while(getline(&line, &len, fp) != -1) { //col = 0; dist = strtok(line, " ,"); dist_max = 0; while(dist != NULL){ dist_d = strtod(dist, &end); dist = strtok(NULL, ","); if (dist_d > dist_max){ dist_max = dist_d; } //col += 1; } if (dist_max < dist_min_max){ dist_min_max = dist_max; } //row += 1; } self->g_thresh = dist_min_max; rewind(fp); #endif EDGE_ID edge_list_ptr = 0; // this is a distance matrix while(getline(&line, &len, fp) != -1) { col = 0; dist = strtok(line, " ,"); while(dist != NULL){ dist_d = strtod(dist, &end); //if (dist_d != 0) dist_d = 1/dist_d; dist = strtok(NULL, ","); if (col > row){ //if (simplex1_check(row, col, dist_d, self->g_thresh)){ if (dist_d < self->g_thresh){ //self->g_edges_list[self->g_n_valid_edges] = (EDGE_ID*)malloc(2*sizeof(EDGE_ID)); // Note that g_edges_list is sorted, row < col //self->g_edges_list[self->g_n_valid_edges][0] = row; //self->g_edges_list[self->g_n_valid_edges][1] = col; self->g_edges_list[edge_list_ptr++] = row; self->g_edges_list[edge_list_ptr++] = col; // parameter self->g_edge_parameter[self->g_n_valid_edges] = dist_d; self->g_n_valid_edges += 1; if (self->g_n_valid_edges == prealloc){ prealloc += 100000; self->g_edges_list = (EDGE_ID*)realloc(self->g_edges_list, 2*prealloc*sizeof(EDGE_ID)); self->g_edge_parameter = (PAR*)realloc(self->g_edge_parameter, prealloc*sizeof(PAR)); } } } col += 1; } row += 1; } self->g_n_vert = row; } else if (self->g_filetype == 1){ self->g_thresh = self->g_thresh * self->g_thresh; //Locations information if (!self->g_suppress_output){ printf("extracting edges"); } int dim_space = 0; while(getline(&line, &len, fp) != -1) { dist = strtok(line, " ,"); while(dist != NULL){ dist_d = strtod(dist, &end); dist = strtok(NULL, ","); dim_space++; } break; } rewind(fp); PAR** locations; locations = (PAR**)malloc(sizeof(PAR*)); while(getline(&line, &len, fp) != -1) { col = 0; if (!self->g_suppress_output){ printf("\rrow %d", row); } locations = (PAR**)realloc(locations, (row+1)*sizeof(PAR*)); locations[row] = (PAR*)malloc(dim_space*sizeof(PAR)); dist = strtok(line, " ,"); while(dist != NULL){ dist_d = strtod(dist, &end); //if (dist_d != 0) dist_d = 1/dist_d; dist = strtok(NULL, ","); locations[row][col++] = dist_d; } row++; } PAR diff; #ifdef POINTCLOUD_MINMAX if (!self->g_suppress_output){ printf("\nthresh is %lf", self->g_thresh); } PAR dist_min_max, dist_max; dist_min_max = INFINITY; for (int i = 0; i < row; i++){ //if (i%1000 == 0) if (!self->g_suppress_output){ printf("\n%d", i); } dist_max = 0; for (int j = 0; j < row; j++){ for (int k = 0; k < dim_space; k++){ diff = locations[i][k] - locations[j][k]; dist_d += diff*diff; } if (dist_d > dist_max){ dist_max = dist_d; } } if (dist_max < dist_min_max){ dist_min_max = dist_max; } } if (self->g_thresh > dist_min_max){ self->g_thresh = dist_min_max; } if (!self->g_suppress_output){ printf("\nupdated thresh is %lf", self->g_thresh); } #endif EDGE_ID edge_list_ptr = 0; if (!self->g_suppress_output){ printf("\n"); } for (int i = 0; i < row-1; i++){ if (!self->g_suppress_output){ printf("Done %f percent edges %d\r", (float)i/(float)(row-1), self->g_n_valid_edges); } for (int j = i+1; j < row; j++){ dist_d = 0; for (int k = 0; k < dim_space; k++){ diff = locations[i][k] - locations[j][k]; dist_d += diff*diff; } //dist_d = sqrt(dist_d); //if (simplex1_check(i, j, dist_d, self->g_thresh)){ if (dist_d < self->g_thresh){ //self->g_edges_list[self->g_n_valid_edges] = (EDGE_ID*)malloc(2*sizeof(EDGE_ID)); // Note that g_edges_list is sorted, row < col //self->g_edges_list[self->g_n_valid_edges][0] = i; //self->g_edges_list[self->g_n_valid_edges][1] = j; self->g_edges_list[edge_list_ptr++] = i; self->g_edges_list[edge_list_ptr++] = j; // parameter self->g_edge_parameter[self->g_n_valid_edges] = dist_d; self->g_n_valid_edges += 1; if (self->g_n_valid_edges == prealloc){ prealloc += 100000; self->g_edges_list = (EDGE_ID*)realloc(self->g_edges_list, 2*prealloc*sizeof(EDGE_ID)); self->g_edge_parameter = (PAR*)realloc(self->g_edge_parameter, prealloc*sizeof(PAR)); } } } } for (int i = 0; i < row; i++) free(locations[i]); free(locations); self->g_n_vert = row; if (!self->g_suppress_output){ printf("\nExtracted edges\n"); } } else if (self->g_filetype == 2){ //List of edges with lengths //Format is v1, v2, length if (!self->g_suppress_output){ printf("extracting edges"); } int n_edges = 0; row = 0; //while(getline(&line, &len, fp) != -1) // n_edges++; //printf("\nnumber of edges %d", n_edges); //rewind(fp); int vv1, vv2; int max_v = 0; EDGE_ID edge_list_ptr = 0; while(getline(&line, &len, fp) != -1) { col = 0; //self->g_edges_list[self->g_n_valid_edges] = (EDGE_ID*)malloc(2*sizeof(EDGE_ID)); dist = strtok(line, " ,"); while(dist != NULL){ if (col == 0){ vv1 = atoi(dist); if (vv1 > max_v) max_v = vv1; } else if (col == 1){ vv2 = atoi(dist); if (vv2 > max_v) max_v = vv2; } else if (col == 2){ PAR edge_length = strtod(dist, &end); //if (simplex1_check(vv1, vv2, edge_length, self->g_thresh)){ if (edge_length < self->g_thresh){ self->g_edge_parameter[self->g_n_valid_edges] = edge_length; if (vv1 < vv2){ //self->g_edges_list[self->g_n_valid_edges][0] = vv1; //self->g_edges_list[self->g_n_valid_edges][1] = vv2; self->g_edges_list[edge_list_ptr++] = vv1; self->g_edges_list[edge_list_ptr++] = vv2; } else { //self->g_edges_list[self->g_n_valid_edges][0] = vv2; //self->g_edges_list[self->g_n_valid_edges][1] = vv1; self->g_edges_list[edge_list_ptr++] = vv2; self->g_edges_list[edge_list_ptr++] = vv1; } self->g_n_valid_edges++; if (self->g_n_valid_edges == prealloc){ prealloc += 100000; self->g_edges_list = (EDGE_ID*)realloc(self->g_edges_list, 2*prealloc*sizeof(EDGE_ID)); self->g_edge_parameter = (PAR*)realloc(self->g_edge_parameter, prealloc*sizeof(PAR)); } } } dist = strtok(NULL, ","); col++; } row++; } self->g_n_vert = max_v+1; if (!self->g_suppress_output){ printf("\nExtracted edges\n"); } } self->g_edges_list = (EDGE_ID*)realloc(self->g_edges_list, 2*self->g_n_valid_edges*sizeof(EDGE_ID)); self->g_edge_parameter = (PAR*)realloc(self->g_edge_parameter, self->g_n_valid_edges*sizeof(PAR)); fclose(fp); free(line); if (!self->g_suppress_output){ printf("\nNumber of vertices %d", self->g_n_vert); } mergeSort(self->g_edge_parameter, self->g_edges_list, 0, self->g_n_valid_edges-1); if (!self->g_suppress_output){ printf("\nSorted %d edges\n", self->g_n_valid_edges); } //exit(0); clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_process_input = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_process_input += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // // STEP 1 // Generate Neighbor matrices // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// //printf("\nPress key to start..."); //getchar(); clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); // Initiate the Neighbor data structures self->g_Neighbors_e = (Neighbors**)malloc(self->g_n_vert*sizeof(Neighbors*)); self->g_Neighbors = (Neighbors**)malloc(self->g_n_vert*sizeof(Neighbors*)); self->g_Neigh_len = (VERT_ID*)calloc(self->g_n_vert, sizeof(VERT_ID)); self->g_pivots_H0 = (EDGE_ID*)calloc(self->g_n_vert, sizeof(EDGE_ID)); EDGE_ID* n_neigh = (EDGE_ID*)calloc(self->g_n_vert, sizeof(EDGE_ID)); VERT_ID vv; for (EDGE_ID i = 0; i < self->g_n_valid_edges; i++){ n_neigh[self->g_edges_list[2*i]]++; n_neigh[self->g_edges_list[(2*i)+1]]++; } for (VERT_ID i = 0; i < self->g_n_vert; i++){ self->g_Neighbors_e[i] = (Neighbors*)malloc(n_neigh[i]*sizeof(Neighbors)); self->g_Neighbors[i] = (Neighbors*)malloc(n_neigh[i]*sizeof(Neighbors)); } free(n_neigh); if (!self->g_suppress_output){ printf("\nCreating neighbors..."); } //double time_create_neigh = omp_get_wtime(); self->g_max_neighbors = 0; for (EDGE_ID i = 0; i < self->g_n_valid_edges; i++){ VERT_ID v1 = self->g_edges_list[2*i]; VERT_ID v2 = self->g_edges_list[(2*i)+1]; len = self->g_Neigh_len[v1]; self->g_Neighbors[v1][len].order = i; self->g_Neighbors[v1][len].neighbor = v2; self->g_Neighbors_e[v1][len].order = i; self->g_Neighbors_e[v1][len].neighbor = v2; self->g_Neigh_len[v1]++; len = self->g_Neigh_len[v2]; self->g_Neighbors[v2][len].order = i; self->g_Neighbors[v2][len].neighbor = v1; self->g_Neighbors_e[v2][len].order = i; self->g_Neighbors_e[v2][len].neighbor = v1; self->g_Neigh_len[v2]++; } //printf("Time taken %f", omp_get_wtime() - time_create_neigh); if (!self->g_suppress_output){ printf("\nSorting neighbors..."); } //double time_sort_neigh = omp_get_wtime(); #pragma omp parallel for schedule(static) shared(self) for (EDGE_ID i = 0; i < self->g_n_vert; i++){ //self->g_Neighbors[i] = (Neighbors*)realloc(self->g_Neighbors[i],\ // self->g_Neigh_len[i]*sizeof(Neighbors)); //self->g_Neighbors_e[i] = (Neighbors*)realloc(self->g_Neighbors_e[i],\ // self->g_Neigh_len[i]*sizeof(Neighbors)); if (self->g_Neigh_len[i] > 1){ sorter_tim_sort(self->g_Neighbors[i], self->g_Neigh_len[i]); sorter2_tim_sort(self->g_Neighbors_e[i], self->g_Neigh_len[i]); } } #ifdef COMBIDX self->g_n_edges = (EDGE_ID)((self->g_n_vert) * (self->g_n_vert-1))/2; self->g_edges_comb_idx = (EDGE_ID*)malloc(self->g_n_edges*sizeof(EDGE_ID)); for (EDGE_ID mm = 0; mm < self->g_n_edges; mm++){ self->g_edges_comb_idx[mm] = self->g_n_valid_edges; } for (EDGE_ID mm = 0; mm < self->g_n_valid_edges; mm++){ EDGE_ID idx = COMB_IDX0(self->g_edges_list[2*mm], self->g_edges_list[2*mm+1]); self->g_edges_comb_idx[idx] = mm; #ifdef DEBUGCOMBIDX VERT_ID idx2 = search_Neighbors(self\ , self->g_edges_list[2*mm]\ , self->g_edges_list[2*mm+1]\ , 0\ , self->g_Neigh_len[self->g_edges_list[2*mm]] - 1); if (idx2 == self->g_n_vert){ if (idx != self->g_n_valid_edges){ printf("\nERRRRROR 0"); getchar(); } } else{ if (self->g_Neighbors[self->g_edges_list[2*mm]][idx2].order != self->g_edges_comb_idx[idx]){ printf("\nERRRRROR 1"); getchar(); } } #endif } #endif clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_neigh = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_neigh += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; //printf("Time taken %f", omp_get_wtime() - time_sort_neigh); //compute_num_simplices(self); //exit(1); /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // // STEP H0.1: Reduce the edges using column method // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// if (!self->g_suppress_output){ printf("\n\n---------------"); printf("\nComputing H0..."); printf("\n---------------\n"); } clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); // R Sparse self->g_R_sparse_max_H0 = 1000; self->g_R_sparse_H0 = (EDGE_ID*)malloc(self->g_R_sparse_max_H0*sizeof(EDGE_ID)); self->g_R_sparse_ptr_H0 = 0; // R sparse col mapping self->g_R_col_indices_max_H0 = 100; self->g_R_col_indices_H0 = (EDGE_ID*)malloc(self->g_R_col_indices_max_H0*sizeof(EDGE_ID)); self->g_R_col_indices_ptr_H0 = 1; // Note which edges have pivots in H0 self->g_edges_with_pivots_H0 = \ (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); //#ifdef HOM_CYCLES // For birth cycles if (self->g_compute_cycles){ self->g_H0_pivot_of = (V_H0*)malloc(self->g_n_vert*sizeof(V_H0)); } //#endif ///////////// // WORKSPACE ///////////// self->g_ws_pre_alloc = 100; self->g_workspace_size = 1000; // H0 workspace structures self->g_R_ws_H0 = \ (EDGE_ID**)malloc(self->g_workspace_size*sizeof(EDGE_ID*)); // H0 workspace info self->g_R_ws_H0_info = (boundary_H0_ws*)malloc(self->g_workspace_size*sizeof(boundary_H0_ws)); // Initialize ws counter self->g_ws_counter = 0; for (int ws_counter = 0; ws_counter < self->g_workspace_size; ws_counter++){ self->g_R_ws_H0_info[ws_counter].max_len = self->g_ws_pre_alloc; self->g_R_ws_H0[ws_counter] = (EDGE_ID*)malloc(2*self->g_R_ws_H0_info[ws_counter].max_len*sizeof(EDGE_ID)); } //////////////////////////////// // Allocate jobs for parallel H0 //////////////////////////////// self->g_jobs = (int*)malloc((self->g_cpu_count + 1)*sizeof(int)); allocate_jobs(self, self->g_workspace_size); int rtn; self->g_threads = (pthread_t *)malloc(self->g_cpu_count*sizeof(pthread_t)); if ((rtn = pthread_mutex_init(&(self->g_thread_lock), NULL)) !=0) fprintf(stderr, "pthread_mutex_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_boss), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_workers), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); // Initialize thread creation self->g_thread_id = 0; self->g_sleeping_threads = 0; self->g_delete_threads = 0; for (int i = 0; i < self->g_cpu_count; i++){ if ((rtn = pthread_create( \ &(self->g_threads[i]) \ , NULL \ , reduce_with_complex_H0 \ , (void*)self)!= 0)) fprintf(stderr, "pthread_create %d", rtn), exit(-1); } // Wait for threads to be initialized pthread_mutex_lock(&(self->g_thread_lock)); while(self->g_sleeping_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ , &(self->g_thread_lock)); } //////////////////////////////// //////////////////////////////// // Main H0 Homology loop //////////////////////////////// for (EDGE_ID i = 0; i < self->g_n_valid_edges; i++){ //printf("Percentage %f\r", (float)i/(float)self->g_n_valid_edges); // //if (i%10000 == 0){ // printf("\rProcessing edge %d", i); //} //////////////////// // Append to workspace_H0 //////////////////// //self->g_ws_simplices_H0[self->g_ws_counter] = i; boundary_H0_ws* this_ws = self->g_R_ws_H0_info + self->g_ws_counter; // coboundary this_ws->cob = i; // Initially, the original is at 0 this_ws->original = 0; // Length this_ws->len = 2; // Non empty this_ws->flag_non_empty = 1; // Recall: edge_list has v_max at 1 and v_min at 0 self->g_R_ws_H0[self->g_ws_counter][0] = self->g_edges_list[2*i]; self->g_R_ws_H0[self->g_ws_counter][1] = self->g_edges_list[2*i+1]; // Pivot this_ws->pivot = self->g_edges_list[2*i+1]; self->g_ws_counter += 1; if (self->g_ws_counter == self->g_workspace_size){ reduce_ws_H0(self); } } // Reduction of final batch while (self->g_ws_counter){ // Allocate the last batch of size g_ws_counter allocate_jobs(self, self->g_ws_counter); reduce_ws_H0(self); } self->g_R_sparse_H0 = (EDGE_ID*)realloc( \ self->g_R_sparse_H0\ , (self->g_R_sparse_ptr_H0+1)*sizeof(EDGE_ID)); self->g_R_col_indices_H0 = (EDGE_ID*)realloc( \ self->g_R_col_indices_H0 \ , (self->g_R_col_indices_ptr_H0+1)*sizeof(EDGE_ID)); ///////////////////////// // Cancel the threads ///////////////////////// self->g_delete_threads = 1; pthread_cond_broadcast(&(self->g_start_workers)); pthread_mutex_unlock(&(self->g_thread_lock)); for (int i = 0; i < self->g_cpu_count; i++){ pthread_join(self->g_threads[i], NULL); } free(self->g_threads); free(self->g_jobs); ////////////////////////////////////////////////// // Clear H0 parallel workspace ////////////////////////////////////////////////// for (int ws_counter = 0; ws_counter < self->g_workspace_size; ws_counter++){ free(self->g_R_ws_H0[ws_counter]); } free(self->g_R_ws_H0); free(self->g_R_ws_H0_info); ///////////////////////// // Write H0 deaths to file ///////////////////////// //// BINARY FILE //FILE* fp2 = fopen("H0_pers_pairs.bin", "wb"); //fwrite(self->g_H0_pers_pairs, sizeof(PAR),self->g_H0_pers_pairs_len, fp2); //fclose(fp2); #ifdef SAVEPD // TEXT FILE FILE* fp2 = fopen(self->g_H0_pers_file, "w"); if (self->g_filetype == 1){ for (EDGE_ID it = 0; it < self->g_n_valid_edges; it++){ if (self->g_edges_with_pivots_H0[it]){ fprintf(fp2, "%.12lf,", sqrt(self->g_edge_parameter[it])); } } } else{ for (EDGE_ID it = 0; it < self->g_n_valid_edges; it++){ if (self->g_edges_with_pivots_H0[it]){ fprintf(fp2, "%.12lf,", self->g_edge_parameter[it]); } } } fclose(fp2); #endif #ifdef PRINT if (!self->g_suppress_output){ printf("\nPers pairs in dim 0"); } if (self->g_filetype == 1){ for (EDGE_ID it = 0; it < self->g_n_valid_edges; it++){ if (self->g_edges_with_pivots_H0[it]){ printf("\n%.12lf,", sqrt(self->g_edge_parameter[it])); } } } else{ for (EDGE_ID it = 0; it < self->g_n_valid_edges; it++){ if (self->g_edges_with_pivots_H0[it]){ printf("\n%.12lf,", self->g_edge_parameter[it]); } } } #endif clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_H0 = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_H0 += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // // STEP coH1.1: Find cohomology now for the edges // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// if (!self->g_suppress_output){ printf("\n\n-----------------"); printf("\nComputing coH1..."); printf("\n-----------------\n"); } //double time_compute_coH1 = omp_get_wtime(); clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); // V sparse EDGE_ID pre_alloc = 1000; self->g_V_sparse_max = pre_alloc; self->g_V_sparse_H1 = (EDGE_ID*)malloc(self->g_V_sparse_max*sizeof(EDGE_ID)); self->g_V_sparse_ptr = 1; self->g_V_sparse_beg_ptr = 1; self->g_V_sparse_end_ptr = 1; self->g_V_col_indices_max = pre_alloc; self->g_V_col_indices = (EDGE_ID*)malloc(self->g_V_col_indices_max*sizeof(EDGE_ID)); self->g_V_col_indices_ptr = 1; //////////////////////////////////////////////////// // INITIALIZE WORKSPACE //////////////////////////////////////////////////// self->g_cohom_ws_size = 100; self->g_V_ws_H1 = (coboundary_H1_ws*)malloc(self->g_cohom_ws_size*sizeof(coboundary_H1_ws)); for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ self->g_V_ws_H1[mm].max_len = 10; self->g_V_ws_H1[mm].last = 0; self->g_V_ws_H1[mm].keys1 = (implicit_keys1*)malloc(self->g_V_ws_H1[mm].max_len*sizeof(implicit_keys1)); for (EDGE_ID nn = 0; nn < self->g_V_ws_H1[mm].max_len; nn++){ self->g_V_ws_H1[mm].keys1[nn].max_len = 10; self->g_V_ws_H1[mm].keys1[nn].last = 0; self->g_V_ws_H1[mm].keys1[nn].flag_empty = 1; self->g_V_ws_H1[mm].keys1[nn].keys2 =\ (implicit_keys2*)malloc(self->g_V_ws_H1[mm].keys1[nn].max_len*sizeof(implicit_keys2)); } self->g_V_ws_H1[mm].v_edges.max_len = 100; self->g_V_ws_H1[mm].v_edges.last = 0; self->g_V_ws_H1[mm].v_edges.o_ab = (EDGE_ID*)malloc(self->g_V_ws_H1[mm].v_edges.max_len*sizeof(EDGE_ID)); } //////////////////////////////////////////////////// // H1 pivots self->g_H1_cohom_pivots = (H1_cohom_pivots**)malloc(self->g_n_valid_edges*sizeof(H1_cohom_pivots*)); self->g_H1_cohom_pivots_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); self->g_H1_cohom_pivots_max_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); // H1 Pers pairs self->g_H1_pers_pairs_max_len = 1000; self->g_H1_pers_pairs_len = 0; self->g_H1_pers_pairs = (PAR*)malloc(self->g_H1_pers_pairs_max_len*sizeof(PAR)); //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H1_undead_ptr = 0; self->g_H1_undead_max = 10; self->g_H1_undead = (EDGE_ID*)malloc(self->g_H1_undead_max*sizeof(EDGE_ID)); } //#endif int new_debug = 0; self->g_coH1_all_lows = (coboundary_H1*)malloc(self->g_n_valid_edges*sizeof(coboundary_H1)); //////////////////////////////////////////////////////////////// // Allocate jobs/threads for parallel coH1 //////////////////////////////////////////////////////////////// self->g_jobs = (int*)malloc((self->g_cpu_count + 1)*sizeof(int)); allocate_jobs(self, self->g_cohom_ws_size); self->g_threads = (pthread_t *)malloc(self->g_cpu_count*sizeof(pthread_t)); if ((rtn = pthread_mutex_init(&(self->g_thread_lock), NULL)) !=0) fprintf(stderr, "pthread_mutex_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_boss), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_workers), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); // Initialize thread creation self->g_thread_id = 0; self->g_sleeping_threads = 0; self->g_delete_threads = 0; for (int i = 0; i < self->g_cpu_count; i++){ if ((rtn = pthread_create( \ &(self->g_threads[i]) \ , NULL \ , reduce_with_complex_coH1 \ , (void*)self)!= 0)) fprintf(stderr, "pthread_create %d", rtn), exit(-1); } // Wait for threads to be initialized pthread_mutex_lock(&(self->g_thread_lock)); while(self->g_sleeping_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ , &(self->g_thread_lock)); } //////////////////////////////// #pragma omp parallel for schedule(static) shared(self) for (EDGE_ID mm = 0; mm < self->g_n_valid_edges; mm++) { self->g_coH1_all_lows[mm].o_ab = mm; find_H1_cohom_low(self, &(self->g_coH1_all_lows[mm])); // Need to find a_ptr and b_ptr if first low.key1 > e if (self->g_coH1_all_lows[mm].low.key1 > self->g_coH1_all_lows[mm].o_ab){ VERT_ID a = self->g_edges_list[2*self->g_coH1_all_lows[mm].o_ab]; VERT_ID b = self->g_edges_list[2*self->g_coH1_all_lows[mm].o_ab+1]; self->g_coH1_all_lows[mm].a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , self->g_coH1_all_lows[mm].low.key1, self->g_Neigh_len[a]); self->g_coH1_all_lows[mm].b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , self->g_coH1_all_lows[mm].low.key1, self->g_Neigh_len[b]); } } self->g_this_edge = self->g_n_valid_edges; /////////////////////////////////////////////////// // MAIN coH1 loop /////////////////////////////////////////////////// //getchar(); self->g_new_debug = 0; self->g_new_debug2 = 0; self->g_ws_counter = 0; //self->g_debug_edge = self->g_n_valid_edges; self->g_debug_edge = 307605; while(self->g_this_edge){ self->g_this_edge--; //if (self->g_this_edge%10000 == 0){ // printf("\nProcessing edge %d", self->g_this_edge); //} /////////////////////////////////////////////////// // CLEARING ALGORITHM // Does this edge have a pivot? /////////////////////////////////////////////////// if (self->g_edges_with_pivots_H0[self->g_this_edge]){ //This edge has a pivot in H0. So, skip it. Continue; //skip++; #ifdef COH1DEBUG if (self->g_this_edge == self->g_debug_edge ){ printf("\nskipping because cleared. so, cannot have anything relevant"); } #endif continue; } /////////////////////////////////////////////////// /////////////////////////////////////////////////// if (self->g_coH1_all_lows[self->g_this_edge].low.key1 == self->g_n_valid_edges){ // This edge has no coboundary //if (self->g_new_debug){ // printf("\nno cob, skipping"); //} // Add this as undead in H1 if (self->g_H1_pers_pairs_len+2 == self->g_H1_pers_pairs_max_len){ self->g_H1_pers_pairs_max_len += 1000; self->g_H1_pers_pairs = (PAR*)realloc(self->g_H1_pers_pairs\ , self->g_H1_pers_pairs_max_len*sizeof(PAR)); } self->g_H1_pers_pairs[self->g_H1_pers_pairs_len++] = \ self->g_edge_parameter[self->g_this_edge]; self->g_H1_pers_pairs[self->g_H1_pers_pairs_len++] = -1; //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H1_undead[self->g_H1_undead_ptr++] = self->g_this_edge; if (self->g_H1_undead_ptr == self->g_H1_undead_max){ self->g_H1_undead_max += 100; self->g_H1_undead = (EDGE_ID*)realloc(self->g_H1_undead\ , self->g_H1_undead_max*sizeof(EDGE_ID)); } } //#endif #ifdef COH1DEBUG if (self->g_this_edge == self->g_debug_edge ){ printf("\nskipping because has no cob"); } #endif continue; } // This is a trivial pair if (self->g_coH1_all_lows[self->g_this_edge].low.key1 == self->g_this_edge){ #ifdef COH1DEBUG if (self->g_this_edge == self->g_debug_edge ){ printf("\nis a trivial pers pair. dont have to add pivot."); } #endif // I DO NOT KNOW WHY I HAVE THIS HERE //self->g_edges_with_pivots_H0[self->g_this_edge] = 10; continue; } #ifdef COH1DEBUG if (self->g_this_edge == self->g_debug_edge ){ printf("\nhave to start reduction"); self->g_new_debug = 1; self->g_new_debug2 = 1; } #endif coboundary_H1_ws* this_ws = self->g_V_ws_H1 + self->g_ws_counter; this_ws->edge = self->g_this_edge; this_ws->pivot = self->g_coH1_all_lows[this_ws->edge].low; this_ws->flag_first = 1; this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 0; this_ws->flag_non_empty = 1; // FIRST ENTRY IN hash-table this_ws->k1_ptr = 0; this_ws->k2_ptr = 0; this_ws->last = 1; this_ws->keys1[0].last = 1; this_ws->keys1[0].flag_empty = 0; this_ws->keys1[0].k1 = this_ws->pivot.key1; this_ws->keys1[0].keys2[0].k2 = this_ws->pivot.key2; this_ws->keys1[0].keys2[0].o_ab = self->g_coH1_all_lows[this_ws->edge].o_ab; this_ws->keys1[0].keys2[0].a_ptr = self->g_coH1_all_lows[this_ws->edge].a_ptr; this_ws->keys1[0].keys2[0].b_ptr = self->g_coH1_all_lows[this_ws->edge].b_ptr; this_ws->keys1[0].keys2[0].flag_next = 1; this_ws->v_edges.last = 0; self->g_ws_counter++; if (self->g_ws_counter == self->g_cohom_ws_size){ reduce_ws_coH1(self); } } while(self->g_ws_counter){ allocate_jobs(self, self->g_ws_counter); reduce_ws_coH1(self); } ///////////////////////// // Cancel the threads used in getting next during reduction ///////////////////////// self->g_delete_threads = 1; pthread_cond_broadcast(&(self->g_start_workers)); pthread_mutex_unlock(&(self->g_thread_lock)); for (int i = 0; i < self->g_cpu_count; i++){ pthread_join(self->g_threads[i], NULL); } free(self->g_threads); free(self->g_jobs); if (!self->g_suppress_output){ printf("\nsparse V coH1 length %d", self->g_V_sparse_ptr); } self->g_H1_pers_pairs = (PAR*)realloc(self->g_H1_pers_pairs, self->g_H1_pers_pairs_len*sizeof(PAR)); //// BINARY FILE //FILE* fp2 = fopen("H1_pers_pairs.bin", "wb"); //fwrite(self->g_H1_pers_pairs, sizeof(PAR),self->g_H1_pers_pairs_len, fp2); //fclose(fp2); #ifdef SAVEPD // TEXT FILE fp2 = fopen(self->g_H1_pers_file, "w"); PAR ddeath; if (self->g_filetype == 1){ for (EDGE_ID it = 0; it < self->g_H1_pers_pairs_len; it+=2){ if (self->g_H1_pers_pairs[it+1] == -1){ ddeath = -1; } else{ ddeath = sqrt(self->g_H1_pers_pairs[it+1]); } fprintf(fp2, "%0.12lf, %0.12lf\n", sqrt(self->g_H1_pers_pairs[it]), ddeath); } } else{ for (EDGE_ID it = 0; it < self->g_H1_pers_pairs_len; it+=2){ fprintf(fp2, "%0.12lf, %0.12lf\n", self->g_H1_pers_pairs[it], self->g_H1_pers_pairs[it+1]); } } fclose(fp2); #endif #ifdef PRINT // TEXT FILE if (!self->g_suppress_output){ printf("\nPers pairs in dim 1"); } if (self->g_filetype == 1){ for (EDGE_ID it = 0; it < self->g_H1_pers_pairs_len; it+=2){ printf("\n%0.12lf, %0.12lf", sqrt(self->g_H1_pers_pairs[it]), sqrt(self->g_H1_pers_pairs[it+1])); } } else{ for (EDGE_ID it = 0; it < self->g_H1_pers_pairs_len; it+=2){ printf("\n%0.12lf, %0.12lf", self->g_H1_pers_pairs[it], self->g_H1_pers_pairs[it+1]); } } #endif #ifdef SAVEV // TEXT FILE fp2 = fopen(self->g_coH1_V_file, "w"); for (EDGE_ID it = 1; it < self->g_V_sparse_max; it++){ fprintf(fp2, "%d\n", self->g_V_sparse_H1[it]); } fclose(fp2); #endif // FREE coH1 Workspace for (int bb = 0; bb < self->g_cohom_ws_size; bb++){ for (int mm = 0; mm < self->g_V_ws_H1[bb].max_len; mm++){ free(self->g_V_ws_H1[bb].keys1[mm].keys2); } free(self->g_V_ws_H1[bb].keys1); free(self->g_V_ws_H1[bb].v_edges.o_ab); } free(self->g_V_ws_H1); // FREE V_sparse free(self->g_V_sparse_H1); clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_coH1 = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_coH1 += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; //printf("Time: %lf\n", elapsed_wall_clock); ///////////////////////////////////////// // Computing H1 homology and birth cycles ///////////////////////////////////////// clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); self->g_timer_computeH1 = 0; self->g_timer_H1cycles = 0; self->g_timer_minimize_H1cycles = 0; //#ifdef HOM_CYCLES if (self->g_compute_cycles) compute_H1_homology_cycles(self); //#endif if (self->g_dim_lim == 1){ if (!self->g_suppress_output){ printf("\nTime to process input : %lf" , self->g_timer_process_input); printf("\nTime to create neigh: %lf" , self->g_timer_neigh); printf("\nTime to compute H0: %lf" , self->g_timer_H0); printf("\nTime to compute coH1: %lf" , self->g_timer_coH1); //#ifdef HOM_CYCLES if (self->g_compute_cycles){ printf("\nTime to compute H1: %lf" , self->g_timer_computeH1); printf("\nTime to compute %llu H1 cycles: %lf" , self->g_n_H1_birth_cycles, self->g_timer_H1cycles); printf("\nStored V_H0 %llu" , self->g_n_H0_stored_V); } //#endif //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths) printf("\nTime to minimize H1 birth cycles: %lf" , self->g_timer_minimize_H1cycles); //#endif //#ifdef MINIMIZE_HOM_CYCLES // printf("\nTime to minimize H1 hom cycles: %lf" , self->g_timer_minimize_H1_homcycles); //#endif printf("\nTotal time taken: %lf", \ self->g_timer_process_input\ + self->g_timer_neigh\ + self->g_timer_H0\ + self->g_timer_coH1\ + self->g_timer_computeH1\ + self->g_timer_H1cycles\ + self->g_timer_minimize_H1cycles\ + self->g_timer_minimize_H1_homcycles\ ); } deallocator(self); if (!self->g_suppress_output){ printf("\nQuitting after coH1"); } //Py_RETURN_NONE; exit(0); } /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // // STEP coH2.1: Find cohomology now for the triangles // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); if (!self->g_suppress_output){ printf("\n\n--------------"); printf("\nComputing coH2"); printf("\n--------------"); } // sparse V coH2 self->g_V_sparse_max = 100000; self->g_V_sparse_H2 = (simplex*)malloc(self->g_V_sparse_max*sizeof(simplex)); self->g_V_sparse_ptr = 1; self->g_V_sparse_beg_ptr = 1; self->g_V_sparse_end_ptr = 1; self->g_V_col_indices_ptr = 1; //////////////////////////////////////////////////// // INITIALIZE WORKSPACE //////////////////////////////////////////////////// self->g_cohom_ws_size = 100; self->g_V_ws_H2 = (coboundary_H2_ws*)malloc(self->g_cohom_ws_size*sizeof(coboundary_H2_ws)); for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ self->g_V_ws_H2[mm].max_len = 10; self->g_V_ws_H2[mm].last = 0; self->g_V_ws_H2[mm].keys1 = (coH2_implicit_keys1*)malloc(self->g_V_ws_H2[mm].max_len*sizeof(coH2_implicit_keys1)); for (EDGE_ID nn = 0; nn < self->g_V_ws_H2[mm].max_len; nn++){ self->g_V_ws_H2[mm].keys1[nn].max_len = 10; self->g_V_ws_H2[mm].keys1[nn].last = 0; self->g_V_ws_H2[mm].keys1[nn].flag_empty = 1; self->g_V_ws_H2[mm].keys1[nn].keys2 =\ (coH2_implicit_keys2*)malloc(self->g_V_ws_H2[mm].keys1[nn].max_len*sizeof(coH2_implicit_keys2)); } self->g_V_ws_H2[mm].v_triangles.max_len = 100; self->g_V_ws_H2[mm].v_triangles.last = 0; self->g_V_ws_H2[mm].v_triangles.o_abc = (simplex*)malloc(self->g_V_ws_H2[mm].v_triangles.max_len*sizeof(simplex)); } //////////////////////////////////////////////////// // PIVOTS self->g_H2_cohom_pivots = (H2_cohom_pivots**)malloc(self->g_n_valid_edges*sizeof(H2_cohom_pivots*)); self->g_H2_cohom_pivots_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); self->g_H2_cohom_pivots_max_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); // H1 Pers pairs self->g_H2_pers_pairs_max_len = 1000; self->g_H2_pers_pairs_len = 0; self->g_H2_pers_pairs = (PAR*)malloc(self->g_H2_pers_pairs_max_len*sizeof(PAR)); //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H2_undead_ptr = 0; self->g_H2_undead_max = 10; self->g_H2_undead = (simplex*)malloc(self->g_H2_undead_max*sizeof(simplex)); } //#endif //////////////////////////////////////////////////////////////// // Allocate jobs/threads for parallel coH2 //////////////////////////////////////////////////////////////// self->g_jobs = (int*)malloc((self->g_cpu_count + 1)*sizeof(int)); allocate_jobs(self, self->g_cohom_ws_size); self->g_threads = (pthread_t *)malloc(self->g_cpu_count*sizeof(pthread_t)); if ((rtn = pthread_mutex_init(&(self->g_thread_lock), NULL)) !=0) fprintf(stderr, "pthread_mutex_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_boss), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_workers), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); // Initialize thread creation self->g_thread_id = 0; self->g_sleeping_threads = 0; self->g_delete_threads = 0; for (int i = 0; i < self->g_cpu_count; i++){ if ((rtn = pthread_create( \ &(self->g_threads[i]) \ , NULL \ , reduce_with_complex_coH2 \ , (void*)self)!= 0)) fprintf(stderr, "pthread_create %d", rtn), exit(-1); } // Wait for threads to be initialized pthread_mutex_lock(&(self->g_thread_lock)); while(self->g_sleeping_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ , &(self->g_thread_lock)); } //////////////////////////////// // BUFFER EDGE_ID buffer_len = 1000000; int buffer_ptr = 0; coboundary_H2* coH2_lows_buffer = (coboundary_H2*)malloc(buffer_len*sizeof(coboundary_H2)); /////////////////////////////////////////////////// // MAIN coH2 loop /////////////////////////////////////////////////// // //EDGE_ID i = self->g_n_valid_edges; coboundary_H2* temp_temp_triangles = (coboundary_H2*)malloc(self->g_n_vert*sizeof(coboundary_H2)); VERT_ID temp_temp_len = 0; coboundary_H2 temp_triangle; self->g_debug_triangle.key1 = self->g_n_valid_edges ; self->g_debug_triangle.key2 = self->g_n_valid_edges ; //self->g_debug_triangle.key1 = 46494 ; //self->g_debug_triangle.key2 = 269 ; VERT_ID a, b, c, a_ptr, b_ptr; EDGE_ID ac, bc, has_pivot; EDGE_ID ab = self->g_n_valid_edges; while(ab){ ab--; if (!self->g_suppress_output){ if (self->g_n_valid_edges > 1000){ if (ab % (self->g_n_valid_edges/100) == 0){ printf("\rProcessing coH2 for edge %d out of %d", ab, self->g_n_valid_edges); } } else{ printf("\rProcessing coH2 for edge %d out of %d", ab, self->g_n_valid_edges); } } a = self->g_edges_list[2*ab]; b = self->g_edges_list[2*ab+1]; // Find the faces which are created when this edge is formed // That means, the o_max will be ab //ab = i; a_ptr = 0; b_ptr = 0; while ((a_ptr < self->g_Neigh_len[a])\ && (b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors[a][a_ptr].neighbor < self->g_Neighbors[b][b_ptr].neighbor) { a_ptr++; } else if (self->g_Neighbors[a][a_ptr].neighbor > self->g_Neighbors[b][b_ptr].neighbor) { b_ptr++; } else{ c = self->g_Neighbors[a][a_ptr].neighbor; //if (!simplex2_check(a, b, c)) continue; ac = self->g_Neighbors[a][a_ptr++].order; bc = self->g_Neighbors[b][b_ptr++].order; if ((ac > ab) \ || (bc > ab)) continue; temp_triangle.triangle.key1 = ab; temp_triangle.triangle.key2 = (EDGE_ID)c; /////////////////////////////////////////////////// // CLEARING ALGORITHM // Does this triangle have a pivot in coH1? /////////////////////////////////////////////////// // Check whether the triangle is pivot of a trivial pair in coH1 if ((self->g_coH1_all_lows[temp_triangle.triangle.key1].low.key1 == temp_triangle.triangle.key1)\ &&(self->g_coH1_all_lows[temp_triangle.triangle.key1].low.key2 == temp_triangle.triangle.key2)){ //printf("\nSkipping"); continue; } // Check whether the triangle is a pivot in coH1 if (self->g_H1_cohom_pivots_len[temp_triangle.triangle.key1]){ has_pivot = search_H1_cohom_pivots(self->g_H1_cohom_pivots[temp_triangle.triangle.key1]\ , 0 \ , self->g_H1_cohom_pivots_len[temp_triangle.triangle.key1] - 1\ , temp_triangle.triangle.key2 \ , self->g_n_valid_edges); if (has_pivot != self->g_n_valid_edges){ //This triangle has a pivot in H1. So, skip it. Continue; //printf("\nSkipping"); //getchar(); continue; } } // END OF CLEARING ALGORITHM /////////////////////////////////////////////////// temp_temp_triangles[temp_temp_len++] = temp_triangle; } } while (temp_temp_len > 0){ temp_temp_len--; coH2_lows_buffer[buffer_ptr++].triangle = temp_temp_triangles[temp_temp_len].triangle; if (buffer_ptr == buffer_len){ #pragma omp parallel for schedule(static) \ shared(self, coH2_lows_buffer) for (EDGE_ID mm = 0; mm < buffer_len; mm++) { find_H2_cohom_low(self, &(coH2_lows_buffer[mm])); } EDGE_ID mm = 0; while (mm < buffer_len){ if (coH2_lows_buffer[mm].vertex == -1){ //If it has empty cob, then it is undead cycle //printf("\n Adding undead for H2"); if (self->g_H2_pers_pairs_len+2 == self->g_H2_pers_pairs_max_len){ self->g_H2_pers_pairs_max_len += 1000; self->g_H2_pers_pairs = (PAR*)realloc(self->g_H2_pers_pairs\ , self->g_H2_pers_pairs_max_len*sizeof(PAR)); } self->g_H2_pers_pairs[self->g_H2_pers_pairs_len++] =\ self->g_edge_parameter[coH2_lows_buffer[mm].triangle.key1]; self->g_H2_pers_pairs[self->g_H2_pers_pairs_len++] = -1; //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H2_undead[self->g_H2_undead_ptr++] = coH2_lows_buffer[mm].triangle; if (self->g_H2_undead_ptr == self->g_H2_undead_max){ self->g_H2_undead_max += 100; self->g_H2_undead = (simplex*)realloc(self->g_H2_undead\ , self->g_H2_undead_max*sizeof(simplex)); } } //#endif mm++; continue; } // Is this is a trivial pair? if ((coH2_lows_buffer[mm].low.key1 == coH2_lows_buffer[mm].triangle.key1)\ &&(self->g_edges_list[2*coH2_lows_buffer[mm].low.key2+1]== coH2_lows_buffer[mm].triangle.key2)){ mm++; continue; } coboundary_H2_ws* this_ws = self->g_V_ws_H2 + self->g_ws_counter; this_ws->triangle = coH2_lows_buffer[mm].triangle; this_ws->pivot = coH2_lows_buffer[mm].low; this_ws->flag_first = 1; this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 0; this_ws->flag_non_empty = 1; this_ws->k1_ptr = 0; this_ws->k2_ptr = 0; this_ws->last = 1; this_ws->keys1[0].last = 1; this_ws->keys1[0].flag_empty = 0; this_ws->keys1[0].k1 = this_ws->pivot.key1; this_ws->keys1[0].keys2[0].k2 = this_ws->pivot.key2; this_ws->keys1[0].keys2[0].o_abc = coH2_lows_buffer[mm].triangle; this_ws->keys1[0].keys2[0].a_ptr = coH2_lows_buffer[mm].a_ptr; this_ws->keys1[0].keys2[0].b_ptr = coH2_lows_buffer[mm].b_ptr; this_ws->keys1[0].keys2[0].c_ptr = coH2_lows_buffer[mm].c_ptr; this_ws->keys1[0].keys2[0].vertex = coH2_lows_buffer[mm].vertex; this_ws->keys1[0].keys2[0].flag_next = 1; this_ws->v_triangles.last = 0; self->g_ws_counter++; if (self->g_ws_counter == self->g_cohom_ws_size){ reduce_ws_coH2(self); } mm++; } buffer_ptr = 0; } } } #pragma omp parallel for schedule(static) \ shared(self, coH2_lows_buffer) for (EDGE_ID mm = 0; mm < buffer_ptr; mm++) { find_H2_cohom_low(self, &(coH2_lows_buffer[mm])); } //for (EDGE_ID mm = 0; mm < buffer_ptr; mm++) { EDGE_ID mm = 0; while (mm < buffer_ptr){ if (coH2_lows_buffer[mm].vertex == -1){ mm++; continue; } // Is this is a trivial pair? if ((coH2_lows_buffer[mm].low.key1 == coH2_lows_buffer[mm].triangle.key1)\ &&(self->g_edges_list[2*coH2_lows_buffer[mm].low.key2+1]== coH2_lows_buffer[mm].triangle.key2)){ mm++; continue; } coboundary_H2_ws* this_ws = self->g_V_ws_H2 + self->g_ws_counter; this_ws->triangle = coH2_lows_buffer[mm].triangle; this_ws->pivot = coH2_lows_buffer[mm].low; this_ws->flag_first = 1; this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 0; this_ws->flag_non_empty = 1; this_ws->k1_ptr = 0; this_ws->k2_ptr = 0; this_ws->last = 1; this_ws->keys1[0].last = 1; this_ws->keys1[0].flag_empty = 0; this_ws->keys1[0].k1 = this_ws->pivot.key1; this_ws->keys1[0].keys2[0].k2 = this_ws->pivot.key2; this_ws->keys1[0].keys2[0].o_abc = coH2_lows_buffer[mm].triangle; this_ws->keys1[0].keys2[0].a_ptr = coH2_lows_buffer[mm].a_ptr; this_ws->keys1[0].keys2[0].b_ptr = coH2_lows_buffer[mm].b_ptr; this_ws->keys1[0].keys2[0].c_ptr = coH2_lows_buffer[mm].c_ptr; this_ws->keys1[0].keys2[0].vertex = coH2_lows_buffer[mm].vertex; this_ws->keys1[0].keys2[0].flag_next = 1; this_ws->v_triangles.last = 0; self->g_ws_counter++; if (self->g_ws_counter == self->g_cohom_ws_size){ reduce_ws_coH2(self); } mm++; } while(self->g_ws_counter){ allocate_jobs(self, self->g_ws_counter); reduce_ws_coH2(self); } ////////////////////////////////////////////////// // Cancel the threads used in getting next during reduction ////////////////////////////////////////////////// self->g_delete_threads = 1; pthread_cond_broadcast(&(self->g_start_workers)); pthread_mutex_unlock(&(self->g_thread_lock)); for (int i = 0; i < self->g_cpu_count; i++){ pthread_join(self->g_threads[i], NULL); } free(self->g_threads); free(self->g_jobs); //printf("\nTime taken to compute coH1 %f", omp_get_wtime() - time_compute_coH1); if (!self->g_suppress_output){ printf("\nsparse V coH2 length %d", self->g_V_sparse_ptr); } ////////////////////////////////////////////////// // FREE coH2 Workspace ////////////////////////////////////////////////// for (int bb = 0; bb < self->g_cohom_ws_size; bb++){ for (int mm = 0; mm < self->g_V_ws_H2[bb].max_len; mm++){ free(self->g_V_ws_H2[bb].keys1[mm].keys2); } free(self->g_V_ws_H2[bb].keys1); free(self->g_V_ws_H2[bb].v_triangles.o_abc); } free(self->g_V_ws_H2); // FREE temp_temp_triangles free(temp_temp_triangles); self->g_H2_pers_pairs = (PAR*)realloc(self->g_H2_pers_pairs, self->g_H2_pers_pairs_len*sizeof(PAR)); // BINARY FILE //fp2 = fopen("H2_pers_pairs.bin", "wb"); //fwrite(self->g_H2_pers_pairs, sizeof(PAR),self->g_H2_pers_pairs_len, fp2); //fclose(fp2); #ifdef SAVEPD // TEXT FILE fp2 = fopen(self->g_H2_pers_file, "w"); if (self->g_filetype == 1){ for (EDGE_ID it = 0; it < self->g_H2_pers_pairs_len; it+=2){ if (self->g_H2_pers_pairs[it+1] == -1){ ddeath = -1; } else{ ddeath = sqrt(self->g_H2_pers_pairs[it+1]); } fprintf(fp2, "%0.12lf, %0.12lf\n", sqrt(self->g_H2_pers_pairs[it]), ddeath); } } else{ for (EDGE_ID it = 0; it < self->g_H2_pers_pairs_len; it+=2){ fprintf(fp2, "%0.12lf, %0.12lf\n", self->g_H2_pers_pairs[it], self->g_H2_pers_pairs[it+1]); } } fclose(fp2); #endif #ifdef PRINT // TEXT FILE if (!self->g_suppress_output){ printf("\nPers pairs in dim 2"); } if (self->g_filetype == 1){ for (EDGE_ID it = 0; it < self->g_H2_pers_pairs_len; it+=2){ printf("\n%0.12lf, %0.12lf", sqrt(self->g_H2_pers_pairs[it]), sqrt(self->g_H2_pers_pairs[it+1])); } } else{ for (EDGE_ID it = 0; it < self->g_H2_pers_pairs_len; it+=2){ printf("\n%0.12lf, %0.12lf", self->g_H2_pers_pairs[it], self->g_H2_pers_pairs[it+1]); } } #endif #ifdef SAVEV // TEXT FILE fp2 = fopen(self->g_coH2_V_file, "w"); for (EDGE_ID it = 1; it < self->g_V_sparse_max; it++){ fprintf(fp2, "%d\n", self->g_V_sparse_H2[it]); } fclose(fp2); #endif // FREE V_sparse free(self->g_V_sparse_H2); clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_coH2 = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_coH2 += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; ///////////////////////////////////////// // Computing H2 homology and birth cycles ///////////////////////////////////////// self->g_timer_computeH2 = 0; self->g_timer_H2cycles = 0; self->g_timer_minimize_H2cycles = 0; //#ifdef HOM_CYCLES if (self->g_compute_cycles) compute_H2_homology_cycles(self); //#endif if (!self->g_suppress_output){ printf("\nTime to process input : %lf" , self->g_timer_process_input); printf("\nTime to create neigh: %lf" , self->g_timer_neigh); printf("\nTime to compute H0: %lf" , self->g_timer_H0); printf("\nTime to compute coH1: %lf" , self->g_timer_coH1); printf("\nTime to compute coH2: %lf" , self->g_timer_coH2); } //#ifdef HOM_CYCLES if (self->g_compute_cycles){ if (!self->g_suppress_output){ printf("\nTime to compute H1: %lf" , self->g_timer_computeH1); printf("\nTime to compute %llu H1cycles: %lf" , self->g_n_H1_birth_cycles, self->g_timer_H1cycles); printf("\nStored V_H0 %llu" , self->g_n_H0_stored_V); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ printf("\nTime to minimize H1 birth cycles: %lf" , self->g_timer_minimize_H1cycles); } //#endif //#ifdef MINIMIZE_HOM_CYCLES // printf("\nTime to minimize H1 hom cycles: %lf" , self->g_timer_minimize_H1_homcycles); //#endif printf("\nTime to compute H2: %lf" , self->g_timer_computeH2); printf("\nTime to compute %llu H2cycles: %lf" , self->g_n_H2_birth_cycles, self->g_timer_H2cycles); printf("\nStored V_H1 %llu" , self->g_n_H1_stored_V); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ printf("\nTime to minimize H2 cycles: %lf" , self->g_timer_minimize_H2cycles); } } //#endif //#ifdef MINIMIZE_HOM_CYCLES //printf("\nTime to minimize H2 hom cycles: %lf" , self->g_timer_minimize_H2_homcycles); //#endif } //#endif //printf("Time to compute coH2 serial: %lf\n" , self->g_timer_coH2_serial); //printf("Time to compute coH2 parallel: %lf\n" , self->g_timer_coH2_parallel); if (!self->g_suppress_output){ printf("\nTotal time taken: %lf",\ self->g_timer_process_input\ + self->g_timer_neigh\ + self->g_timer_H0\ + self->g_timer_coH1\ + self->g_timer_coH2\ + self->g_timer_computeH1\ + self->g_timer_computeH2\ + self->g_timer_H1cycles\ + self->g_timer_H2cycles\ + self->g_timer_minimize_H1cycles\ + self->g_timer_minimize_H2cycles\ + self->g_timer_minimize_H1_homcycles\ + self->g_timer_minimize_H2_homcycles\ ); } //printf("Time in H2_low: %lf\n", self->g_timer_H2_low); //printf("Time in H2_greater: %lf\n", self->g_timer_H2_greater); //printf("Time in H2_next: %lf\n", self->g_timer_H2_next); deallocator(self); if (!self->g_suppress_output){ printf("\nQuitting after coH2"); } //Py_RETURN_NONE; } VERT_ID search_Neighbors(filtration* self, VERT_ID v1, VERT_ID v2, VERT_ID l, VERT_ID r){ if (r >= l) { VERT_ID mid = l + (r - l) / 2; // If the element is present at the middle // itself if (self->g_Neighbors[v1][mid].neighbor == v2) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (self->g_Neighbors[v1][mid].neighbor > v2){ if (!mid) return self->g_n_vert; return search_Neighbors(self, v1, v2, l, mid - 1); } // Else the element can only be present // in right subarray return search_Neighbors(self, v1, v2, mid + 1, r); } // We reach here when element is not // present in array return self->g_n_vert; } VERT_ID search_Neighbors_e(filtration* self, VERT_ID v1, EDGE_ID order, VERT_ID l, VERT_ID r, EDGE_ID len){ int mid = l + (r - l) / 2; if (self->g_Neighbors_e[v1][mid].order < order){ if (mid < len-1) if (self->g_Neighbors_e[v1][mid+1].order > order) return mid+1; return search_Neighbors_e(self, v1, order, mid+1, r, len); } else if (self->g_Neighbors_e[v1][mid].order > order){ if (!mid) return 0; return search_Neighbors_e(self, v1, order, l, mid-1, len); } else{ return mid+1; } } ////////////////////////////////////////////////////////// // MERGING ALGORITHMS ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // END OF MERGING ALGORITHMS ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // CUSTOM BOUNDARIES ////////////////////////////////////////////////////////// int simplex1_check(VERT_ID v1, VERT_ID v2, PAR dist, PAR thresh){ if (dist == -1){ return 0; } //if (dist == 0){ // return 0; //} if (dist > thresh){ return 0; } return 1; } int simplex2_check(VERT_ID v1, VERT_ID v2, VERT_ID v3){ return 1; } int simplex3_check(VERT_ID v1, VERT_ID v2, VERT_ID v3, VERT_ID v4){ return 1; } ////////////////////////////////////////////////////////// int compare_simplices(simplex* s1, simplex* s2){ // returns 1 if s1 > s2 // returns 0 if s1 < s2 // returns -1 if s1 = s2 if (s1->key1 > s2->key1) return 1; else if (s1->key1 < s2->key1) return 0; else{ if (s1->key2 > s2->key2) return 1; else if (s1->key2 < s2->key2) return 0; else return -1; } } int compare_simplices_keys(EDGE_ID key11, EDGE_ID key12 \ , EDGE_ID key21, EDGE_ID key22 \ ){ // returns 1 if s1 > s2 // returns 0 if s1 < s2 // returns -1 if s1 = s2 if (key11 > key21) return 1; else if (key11 < key21) return 0; else{ if (key12 > key22) return 1; else if (key12 < key22) return 0; else return -1; } } void find_H1_cohom_low(filtration* self, coboundary_H1* V_info){ VERT_ID a = self->g_edges_list[2*V_info->o_ab]; VERT_ID b = self->g_edges_list[2*V_info->o_ab+1]; V_info->a_ptr = 0; V_info->b_ptr = 0; EDGE_ID o_min = self->g_n_valid_edges; EDGE_ID v_min = 0; EDGE_ID o_s, v_s; while(1){ if ((V_info->a_ptr < self->g_Neigh_len[a]) \ && (V_info->b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors[a][V_info->a_ptr].neighbor < self->g_Neighbors[b][V_info->b_ptr].neighbor){ V_info->a_ptr++; } else if (self->g_Neighbors[a][V_info->a_ptr].neighbor > self->g_Neighbors[b][V_info->b_ptr].neighbor){ V_info->b_ptr++; } else{ EDGE_ID ac = self->g_Neighbors[a][V_info->a_ptr].order; EDGE_ID bc = self->g_Neighbors[b][V_info->b_ptr].order; EDGE_ID c = self->g_Neighbors[a][V_info->a_ptr].neighbor; //printf("\n a, b, c: %d, %d, %d", a, b, c); //printf("\n ab, ac, bc: %d, %d, %d", V_info->o_ab, ac, bc); o_s = ac; v_s = b; if (bc > ac){ o_s = bc; v_s = a; } if (o_s < V_info->o_ab){ V_info->low.key1 = V_info->o_ab; V_info->low.key2 = c; return; } // Reached here means o_s > o_ab //printf("\n o_s, v_s, : %d, %d", o_s, v_s); if (o_s < o_min){ o_min = o_s; v_min = v_s; } else if ((o_s == o_min) && (v_s < v_min)){ v_min = v_s; } //printf("\n o_min, v_min, : %d, %d", o_min, v_min); V_info->a_ptr++; V_info->b_ptr++; } } else{ //printf("\nReturning lowest of > a(%d)b(%d) (%d, %d)", o_s, v_s); V_info->low.key1 = o_min; V_info->low.key2 = v_min; return; } } } // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 EDGE_ID search_H1_cohom_pivots(H1_cohom_pivots* arr, EDGE_ID l, EDGE_ID r, EDGE_ID key2, EDGE_ID max) { if (r >= l) { EDGE_ID mid = l + (r - l) / 2; if (arr[mid].key2 == key2) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid].key2 > key2) { /// PRECAUTIONARY: CAN REMOVE LATER if (!mid){ return max; printf("\nMID 0 WILL GIVE ERROR FOR UNSIGNED NEXT"); getchar(); } /////////////////// return search_H1_cohom_pivots(arr, l, mid - 1, key2, max); } // Else the element can only be present // in right subarray return search_H1_cohom_pivots(arr, mid + 1, r, key2, max); } // We reach here when element is not // present in array //printf("\nNOT FOUND"); return max; } //// A recursive binary search function. It returns //// location of x in given array arr[l..r] is present, //// otherwise -1 //EDGE_ID bin_search_min_update_V(min_update_V* arr, EDGE_ID l, EDGE_ID r, EDGE_ID mm, EDGE_ID max) //{ // if (r >= l) { // EDGE_ID mid = l + (r - l) / 2; // // if (arr[mid].mm == mm) // return mid; // // // If element is smaller than mid, then // // it can only be present in left subarray // if (arr[mid].mm > mm) // { // // /// PRECAUTIONARY: CAN REMOVE LATER // if (!mid){ // return max; // printf("\nMID 0 WILL GIVE ERROR FOR UNSIGNED NEXT"); // getchar(); // } // /////////////////// // return bin_search_min_update_V(arr, l, mid - 1, mm, max); // } // // // Else the element can only be present // // in right subarray // return bin_search_min_update_V(arr, mid + 1, r, mm, max); // } // // // We reach here when element is not // // present in array // //printf("\nNOT FOUND"); // return max; //} // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 EDGE_ID bin_search_cycle_ops(EDGE_ID* arr, EDGE_ID l, EDGE_ID r, EDGE_ID mm, EDGE_ID max) { if (r >= l) { EDGE_ID mid = l + (r - l) / 2; if (arr[mid] == mm) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > mm) { /// PRECAUTIONARY: CAN REMOVE LATER if (!mid){ return max; printf("\nMID 0 WILL GIVE ERROR FOR UNSIGNED NEXT"); getchar(); } /////////////////// return bin_search_cycle_ops(arr, l, mid - 1, mm, max); } // Else the element can only be present // in right subarray return bin_search_cycle_ops(arr, mid + 1, r, mm, max); } // We reach here when element is not // present in array //printf("\nNOT FOUND"); return max; } // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 EDGE_ID bin_search_cyc_in_cyc(cyc_in_cyc* arr, EDGE_ID l, EDGE_ID r, EDGE_ID mm, EDGE_ID max) { if (r >= l) { EDGE_ID mid = l + (r - l) / 2; if (arr[mid].cj == mm) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid].cj > mm) { /// PRECAUTIONARY: CAN REMOVE LATER if (!mid){ return max; printf("\nMID 0 WILL GIVE ERROR FOR UNSIGNED NEXT"); getchar(); } /////////////////// return bin_search_cyc_in_cyc(arr, l, mid - 1, mm, max); } // Else the element can only be present // in right subarray return bin_search_cyc_in_cyc(arr, mid + 1, r, mm, max); } // We reach here when element is not // present in array //printf("\nNOT FOUND"); return max; } // returns greater than or equal to void find_H1_cohom_greater(filtration* self, coboundary_H1* V_info, simplex* pivot){ //EDGE_ID o_min = self->g_n_valid_edges; //EDGE_ID v_min = 0; if (pivot->key1 < V_info->o_ab){ // Find first low of o_ab find_H1_cohom_low(self, V_info); // If it has a low if (V_info->low.key1 < self->g_n_valid_edges){ // Need to find a_ptr and b_ptr if first low.key1 > e if (V_info->low.key1 > V_info->o_ab){ VERT_ID a = self->g_edges_list[2*V_info->o_ab]; VERT_ID b = self->g_edges_list[2*V_info->o_ab+1]; V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , V_info->low.key1, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , V_info->low.key1, self->g_Neigh_len[b]); } } return; } else if (pivot->key1 == V_info->o_ab){ VERT_ID a = self->g_edges_list[2*V_info->o_ab]; VERT_ID b = self->g_edges_list[2*V_info->o_ab+1]; V_info->a_ptr = 0; V_info->b_ptr = 0; EDGE_ID o_min = self->g_n_valid_edges; EDGE_ID v_min; EDGE_ID o_s; EDGE_ID v_s; V_info->a_ptr = bin_search_min_geq_N(self->g_Neighbors[a], 0, self->g_Neigh_len[a]-1\ , pivot->key2, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_N(self->g_Neighbors[b], 0, self->g_Neigh_len[b]-1\ , pivot->key2, self->g_Neigh_len[b]); if ((self->g_Neighbors[a][V_info->a_ptr].neighbor == pivot->key2) \ && (self->g_Neighbors[b][V_info->b_ptr].neighbor == pivot->key2)){ V_info->low.key1 = V_info->o_ab; V_info->low.key2 = pivot->key2; return; } while(1) { if ((V_info->a_ptr < self->g_Neigh_len[a]) \ && (V_info->b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors[a][V_info->a_ptr].neighbor < self->g_Neighbors[b][V_info->b_ptr].neighbor) { V_info->a_ptr++; } else if (self->g_Neighbors[a][V_info->a_ptr].neighbor > self->g_Neighbors[b][V_info->b_ptr].neighbor) { V_info->b_ptr++; } else { EDGE_ID o_ac = self->g_Neighbors[a][V_info->a_ptr].order; EDGE_ID o_bc = self->g_Neighbors[b][V_info->b_ptr].order; EDGE_ID c = self->g_Neighbors[b][V_info->b_ptr].neighbor; o_s = o_ac; v_s = b; if (o_bc > o_s){ o_s = o_bc; v_s = a; } if (o_s < V_info->o_ab){ if ((c > pivot->key2) || (c == pivot->key2)) { V_info->low.key1 = V_info->o_ab; V_info->low.key2 = c; return; } } else{ if (o_s < o_min){ o_min = o_s; v_min = v_s; } else if (o_s == o_min){ if (v_s < v_min){ v_min = v_s; } } } V_info->a_ptr++; V_info->b_ptr++; } } else{ if (o_min != self->g_n_valid_edges){ V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , o_min, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , o_min, self->g_Neigh_len[b]); } V_info->low.key1 = o_min; V_info->low.key2 = v_min; return; } } } else { VERT_ID a = self->g_edges_list[2*V_info->o_ab]; VERT_ID b = self->g_edges_list[2*V_info->o_ab+1]; V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , pivot->key1, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , pivot->key1, self->g_Neigh_len[b]); //printf("\na_len b_len %d, %d", self->g_Neigh_len[a], self->g_Neigh_len[b]); while (1) { //printf("\nptrs are %d, %d", V_info->a_ptr, V_info->b_ptr); //getchar(); if ((V_info->a_ptr < self->g_Neigh_len[a]) \ && (V_info->b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors_e[a][V_info->a_ptr].order < self->g_Neighbors_e[b][V_info->b_ptr].order){ EDGE_ID o_ac = self->g_Neighbors_e[a][V_info->a_ptr].order; VERT_ID c = self->g_Neighbors_e[a][V_info->a_ptr].neighbor; VERT_ID idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); if (idx < self->g_n_vert) { EDGE_ID o_bc = self->g_Neighbors[b][idx].order; if (o_bc < o_ac){ if ((o_ac > pivot->key1)\ ||((o_ac == pivot->key1) && (b > pivot->key2))\ ||((o_ac == pivot->key1) && (b == pivot->key2))){ V_info->low.key1 = o_ac; V_info->low.key2 = b; return; } } } //else{ V_info->a_ptr++; //} } else { EDGE_ID o_bc = self->g_Neighbors_e[b][V_info->b_ptr].order; VERT_ID c = self->g_Neighbors_e[b][V_info->b_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_ac = COMB_IDX(a, c); if (o_ac != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); if (idx < self->g_n_vert) { EDGE_ID o_ac = self->g_Neighbors[a][idx].order; #endif if (o_ac < o_bc){ if ((o_bc > pivot->key1)\ ||((o_bc == pivot->key1) && (a > pivot->key2))\ ||((o_bc == pivot->key1) && (a == pivot->key2))){ V_info->low.key1 = o_bc; V_info->low.key2 = a; return; } } } //else{ V_info->b_ptr++; //} } } else if (V_info->a_ptr < self->g_Neigh_len[a]){ //Here b_ptr has reached end. So, o_bc should be less than o_ac EDGE_ID o_ac = self->g_Neighbors_e[a][V_info->a_ptr].order; VERT_ID c = self->g_Neighbors_e[a][V_info->a_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_bc = COMB_IDX(b, c); if (o_bc != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); if (idx < self->g_n_vert) { #endif // check if errors //if (o_bc > o_ac){ // printf("\nError check obc_oac"); // getchar(); //} if ((o_ac > pivot->key1)\ ||((o_ac == pivot->key1) && (b > pivot->key2))\ ||((o_ac == pivot->key1) && (b == pivot->key2))){ V_info->low.key1 = o_ac; V_info->low.key2 = b; return; } } //else{ V_info->a_ptr++; //} } else if (V_info->b_ptr < self->g_Neigh_len[b]){ //Here b_ptr has reached end. So, o_ac should be less than o_bc EDGE_ID o_bc = self->g_Neighbors_e[b][V_info->b_ptr].order; VERT_ID c = self->g_Neighbors_e[b][V_info->b_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_ac = COMB_IDX(a, c); if (o_ac != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); if (idx < self->g_n_vert) { #endif // check if errors //if (o_ac > o_bc){ // printf("\nError check obc_oac"); // getchar(); //} if ((o_bc > pivot->key1)\ ||((o_bc == pivot->key1) && (a > pivot->key2))\ ||((o_bc == pivot->key1) && (a == pivot->key2))){ V_info->low.key1 = o_bc; V_info->low.key2 = a; return; } } //else{ V_info->b_ptr++; //} } else{ break; } } V_info->low.key1 = self->g_n_valid_edges; return; } } void find_H1_cohom_next (filtration* self, coboundary_H1* V_info){ VERT_ID a = self->g_edges_list[2*V_info->o_ab]; VERT_ID b = self->g_edges_list[2*V_info->o_ab+1]; //printf("\nLOW of %d is (%d, %d)", V_info->o_ab, V_info->low.key1, V_info->low.key2); // //printf("\nCurrent c, ac, c, bc %d, %d, %d, %d", self->g_Neighbors[a][V_info->a_ptr].neighbor\ // , self->g_Neighbors[a][V_info->a_ptr].order\ // , self->g_Neighbors[b][V_info->b_ptr].neighbor\ // , self->g_Neighbors[b][V_info->b_ptr].order\ // ); if (V_info->o_ab == V_info->low.key1){ V_info->a_ptr++; V_info->b_ptr++; //printf("\naptr, max, bptr, max %d, %d, %d, %d", V_info->a_ptr\ // , self->g_Neigh_len[a]\ // , V_info->b_ptr\ // , self->g_Neigh_len[b]); // //printf("\nstarting loop1"); //EDGE_ID o_min = self->g_n_valid_edges; //EDGE_ID v_min; while (1){ //printf("\naptr, max, bptr, max %d, %d, %d, %d", V_info->a_ptr\ // , self->g_Neigh_len[a]\ // , V_info->b_ptr\ // , self->g_Neigh_len[b]); if ((V_info->a_ptr < self->g_Neigh_len[a]) \ && (V_info->b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors[a][V_info->a_ptr].neighbor < self->g_Neighbors[b][V_info->b_ptr].neighbor){ V_info->a_ptr++; } else if (self->g_Neighbors[a][V_info->a_ptr].neighbor > self->g_Neighbors[b][V_info->b_ptr].neighbor){ V_info->b_ptr++; } else{ EDGE_ID o_ac = self->g_Neighbors[a][V_info->a_ptr].order; EDGE_ID o_bc = self->g_Neighbors[b][V_info->b_ptr].order; EDGE_ID c = self->g_Neighbors[b][V_info->b_ptr].neighbor; //printf("\nINSIDE FOUND NEXT COMMON %d", c); EDGE_ID o_s = o_ac; EDGE_ID v_s = b; if (o_bc > o_ac) { o_s = o_bc; v_s = a; } if (o_s < V_info->low.key1) { V_info->low.key2 = c; //printf("\nReturn 1 "); return; } //else if (o_s < o_min){ // // o_min = o_s; // v_min = v_s; // //} //else if ((o_s == o_min) && (v_s < v_min)){ // v_min = v_s; //} V_info->a_ptr++; V_info->b_ptr++; } } else { break; } } //printf("\nended loop1"); //printf("\nsearching ptrs"); V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a] - 1\ , V_info->o_ab, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b] - 1\ , V_info->o_ab, self->g_Neigh_len[b]); //if (o_min < self->g_n_valid_edges){ // // V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a] - 1\ // , o_min, self->g_Neigh_len[a]); // V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b] - 1\ // , o_min, self->g_Neigh_len[b]); //} //V_info->low.key1 = o_min; //V_info->low.key2 = v_min; //printf("\nReturn 3 "); //return; } // Here //V_info->low.key1 > V_info->o_ab //printf("\norders are ac: %d, bc: %d", self->g_Neighbors_e[a][V_info->a_ptr].order\ // , self->g_Neighbors_e[b][V_info->b_ptr].order); if ((V_info->a_ptr < self->g_Neigh_len[a]) \ && (V_info->b_ptr < self->g_Neigh_len[b])){ if ((self->g_Neighbors_e[a][V_info->a_ptr].order < self->g_Neighbors_e[b][V_info->b_ptr].order)){ V_info->a_ptr++; } else{ V_info->b_ptr++; } } else{ if (V_info->a_ptr < self->g_Neigh_len[a]){ V_info->a_ptr++; } else{ V_info->b_ptr++; } } //printf("\nstarting loop2"); while (1){ //printf("\naptr, max, bptr, max %d, %d, %d, %d", V_info->a_ptr\ // , self->g_Neigh_len[a]\ // , V_info->b_ptr\ // , self->g_Neigh_len[b]); if ((V_info->a_ptr < self->g_Neigh_len[a]) \ && (V_info->b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors_e[a][V_info->a_ptr].order < self->g_Neighbors_e[b][V_info->b_ptr].order) { EDGE_ID o_ac = self->g_Neighbors_e[a][V_info->a_ptr].order; EDGE_ID c = self->g_Neighbors_e[a][V_info->a_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_bc = COMB_IDX(b, c); if (o_bc != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); if (idx < self->g_n_vert) { EDGE_ID o_bc = self->g_Neighbors[b][idx].order; #endif if (o_bc < o_ac){ V_info->low.key1 = o_ac; V_info->low.key2 = b; //printf("\nReturn 4 "); return; } } V_info->a_ptr++; } else{ EDGE_ID o_bc = self->g_Neighbors_e[b][V_info->b_ptr].order; EDGE_ID c = self->g_Neighbors_e[b][V_info->b_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_ac = COMB_IDX(a, c); if (o_ac != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); if (idx < self->g_n_vert) { EDGE_ID o_ac = self->g_Neighbors[a][idx].order; #endif if (o_ac < o_bc){ V_info->low.key1 = o_bc; V_info->low.key2 = a; //printf("\nReturn 5 "); return; } } V_info->b_ptr++; } } else if (V_info->a_ptr < self->g_Neigh_len[a]){ EDGE_ID o_ac = self->g_Neighbors_e[a][V_info->a_ptr].order; EDGE_ID c = self->g_Neighbors_e[a][V_info->a_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_bc = COMB_IDX(b, c); if (o_bc != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); if (idx < self->g_n_vert) { #endif //EDGE_ID o_bc = self->g_Neighbors[b][idx]; // SHOULD HAVE THE NEED TO CHECK //if (o_bc < o_ac){ V_info->low.key1 = o_ac; V_info->low.key2 = b; //printf("\nReturn 5 "); return; //} } V_info->a_ptr++; } else if (V_info->b_ptr < self->g_Neigh_len[b]){ EDGE_ID o_bc = self->g_Neighbors_e[b][V_info->b_ptr].order; EDGE_ID c = self->g_Neighbors_e[b][V_info->b_ptr].neighbor; #ifdef COMBIDX EDGE_ID o_ac = COMB_IDX(a, c); if (o_ac != self->g_n_valid_edges){ #else VERT_ID idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); if (idx < self->g_n_vert) { #endif //EDGE_ID o_bc = self->g_Neighbors[b][idx]; // SHOULD HAVE THE NEED TO CHECK //if (o_bc < o_ac){ V_info->low.key1 = o_bc; V_info->low.key2 = a; //printf("\nReturn 6 "); return; //} } V_info->b_ptr++; } else{ break; } } //printf("\nended loop2"); V_info->low.key1 = self->g_n_valid_edges; //printf("\nReturn 7 "); return; } EDGE_ID bin_search_min_geq_Ne(Neighbors* arr, VERT_ID l, VERT_ID r, VERT_ID x, EDGE_ID MAX){ if (arr[r].order < x){ return MAX; } if (arr[l].order > x){ return l; } VERT_ID mid = l + (r-l)/2; if (arr[mid].order < x){ l = mid + 1; if ((arr[l].order > x) || (arr[l].order == x)){ return l; } bin_search_min_geq_Ne(arr, l, r, x, MAX); } else{ r = mid; if (arr[r].order == x) return r; bin_search_min_geq_Ne(arr, l , r, x, MAX); } } EDGE_ID bin_search_min_geq_N(Neighbors* arr, VERT_ID l, VERT_ID r, VERT_ID x, EDGE_ID MAX){ if (arr[r].neighbor < x){ return MAX; } if (arr[l].neighbor > x){ return l; } VERT_ID mid = l + (r-l)/2; if (arr[mid].neighbor < x){ l = mid + 1; if ((arr[l].neighbor > x) || (arr[l].neighbor == x)){ return l; } bin_search_min_geq_N(arr, l, r, x, MAX); } else{ r = mid; if (arr[r].neighbor == x) return r; bin_search_min_geq_N(arr, l , r, x, MAX); } } void find_H2_cohom_low (filtration* self, coboundary_H2* V_info){ V_info->c_ptr = 0; //int flag = H2_case1 (self, V_info); if (H2_case1(self, V_info)){ return; } VERT_ID a = self->g_edges_list[2*V_info->triangle.key1]; VERT_ID b = self->g_edges_list[2*V_info->triangle.key1+1]; V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , V_info->triangle.key1, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , V_info->triangle.key1, self->g_Neigh_len[b]); V_info->a_ptr++; V_info->b_ptr++; H2_case2(self, V_info); } void find_H2_cohom_next (filtration* self, coboundary_H2* V_info){ //clock_gettime(CLOCK_MONOTONIC, &(self->g_start_wall_clock)); //printf("\nfinding H2 next"); EDGE_ID o_ab = V_info->triangle.key1; //VERT_ID c = V_info->triangle.key2; VERT_ID a = self->g_edges_list[2*o_ab]; VERT_ID b = self->g_edges_list[2*o_ab+1]; //EDGE_ID o_ad, o_bd; //VERT_ID idxa, idxb, d; int flag = 0; //if (V_info->low.key1 == o_ab){ if (V_info->vertex == 0){ V_info->c_ptr++; if (H2_case1(self, V_info)){ return; } // Here means that we did not return and // not a_ptr and b_ptr are at o_ab // So, both need to be incremented V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , V_info->triangle.key1, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , V_info->triangle.key1, self->g_Neigh_len[b]); V_info->a_ptr++; V_info->b_ptr++; flag = 1; } if (!flag){ if (V_info->vertex == 1){ V_info->a_ptr++; } else if (V_info->vertex == 2){ V_info->b_ptr++; } else if (V_info->vertex == 3){ V_info->c_ptr++; } } H2_case2(self, V_info); } void find_H2_cohom_greater (filtration* self, coboundary_H2* V_info, simplex* pivot){ //if (self->g_p_flag){ // printf("\nfinding H2 greater than (%d, %d) for (%d, %d)", pivot->key1, pivot->key2 // , V_info->triangle.key1\ // , V_info->triangle.key2); // getchar(); //} //EDGE_ID o_ab; VERT_ID c, a, b; if (pivot->key1 < V_info->triangle.key1){ // Find first low of o_ab find_H2_cohom_low(self, V_info); return; } else if (pivot->key1 == V_info->triangle.key1){ //o_ab = V_info->triangle.key1; VERT_ID c = V_info->triangle.key2; //a = self->g_edges_list[o_ab][0]; //b = self->g_edges_list[o_ab][1]; V_info->c_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[c], 0, self->g_Neigh_len[c]-1\ , pivot->key2, self->g_Neigh_len[c]); if (self->g_Neighbors_e[c][V_info->c_ptr].order == pivot->key2){ V_info->low = *pivot; V_info->vertex= 0; return; } if (H2_case1(self, V_info)){ return; } // Here means that we did not return and // not a_ptr and b_ptr are at o_ab // So, both need to be incremented a = self->g_edges_list[2*V_info->triangle.key1]; b = self->g_edges_list[2*V_info->triangle.key1+1]; V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , V_info->triangle.key1, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , V_info->triangle.key1, self->g_Neigh_len[b]); V_info->a_ptr++; V_info->b_ptr++; } else{ c = V_info->triangle.key2; a = self->g_edges_list[2*V_info->triangle.key1]; b = self->g_edges_list[2*V_info->triangle.key1+1]; V_info->a_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[a], 0, self->g_Neigh_len[a]-1\ , pivot->key1, self->g_Neigh_len[a]); V_info->b_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[b], 0, self->g_Neigh_len[b]-1\ , pivot->key1, self->g_Neigh_len[b]); V_info->c_ptr = bin_search_min_geq_Ne(self->g_Neighbors_e[c], 0, self->g_Neigh_len[c]-1\ , pivot->key1, self->g_Neigh_len[c]); } while (1){ H2_case2(self, V_info); if (((V_info->low.key1 == pivot->key1) && (V_info->low.key2 > pivot->key2))\ ||(V_info->low.key1 > pivot->key1) || (V_info->low.key1 == self->g_n_valid_edges)\ ||((V_info->low.key1 == pivot->key1) && (V_info->low.key2 == pivot->key2)) ){ break; } if (V_info->vertex == 1){ V_info->a_ptr++; } else if (V_info->vertex == 2){ V_info->b_ptr++; } else if (V_info->vertex == 3){ V_info->c_ptr++; } } } // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 EDGE_ID search_H2_cohom_pivots(H2_cohom_pivots* arr, EDGE_ID l, EDGE_ID r, EDGE_ID key2, EDGE_ID max) { if (r >= l) { EDGE_ID mid = l + (r - l) / 2; if (arr[mid].key2 == key2) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid].key2 > key2) { /// PRECAUTIONARY: CAN REMOVE LATER if (!mid){ return max; printf("\nMID 0 WILL GIVE ERROR FOR UNSIGNED NEXT"); getchar(); } /////////////////// return search_H2_cohom_pivots(arr, l, mid - 1, key2, max); } // Else the element can only be present // in right subarray return search_H2_cohom_pivots(arr, mid + 1, r, key2, max); } // We reach here when element is not // present in array //printf("\nNOT FOUND"); return max; } // Reduces with complex in parallel void* reduce_with_complex_H0(void* arg){ filtration* self = arg; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_mutex_lock(&(self->g_thread_lock)); int tid = ++self->g_thread_id; for (;;){ self->g_sleeping_threads++; if (self->g_sleeping_threads == self->g_cpu_count) pthread_cond_signal(&(self->g_start_boss)); pthread_cond_wait(&(self->g_start_workers), &(self->g_thread_lock)); if (self->g_delete_threads){ //printf("\nexiting from thread %d", tid); pthread_mutex_unlock(&(self->g_thread_lock)); pthread_exit(NULL); } self->g_sleeping_threads--; pthread_mutex_unlock(&(self->g_thread_lock)); for (int ws_counter = self->g_jobs[tid - 1]; ws_counter < self->g_jobs[tid]; ws_counter++){ boundary_H0_ws* this_ws = self->g_R_ws_H0_info + ws_counter; EDGE_ID* orig = self->g_R_ws_H0[ws_counter] + this_ws->original*this_ws->max_len; this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 1; EDGE_ID idx = self->g_pivots_H0[this_ws->pivot]; while(idx){ //reduced_col = self->g_pivots[self->g_dim_now][idx].red_col; //reduced_col = self->g_pivots_H0[idx]; EDGE_ID red_start_idx = self->g_R_col_indices_H0[idx]; EDGE_ID red_finish_idx = self->g_R_col_indices_H0[idx+1]; EDGE_ID red_len = red_finish_idx - red_start_idx; if ((this_ws->len + red_len) > this_ws->max_len){ if (this_ws->original){ for (EDGE_ID it=0; it < this_ws->len; it++){ self->g_R_ws_H0[ws_counter][it] = \ self->g_R_ws_H0[ws_counter][it + this_ws->max_len]; } this_ws->original = 0; } this_ws->max_len = this_ws->len + red_len + 100; pthread_mutex_lock(&(self->g_thread_lock)); self->g_R_ws_H0[ws_counter] = (EDGE_ID*)realloc(self->g_R_ws_H0[ws_counter]\ , 2*this_ws->max_len*sizeof(EDGE_ID)); pthread_mutex_unlock(&(self->g_thread_lock)); orig = self->g_R_ws_H0[ws_counter]; } EDGE_ID* scratch = self->g_R_ws_H0[ws_counter] + (1-this_ws->original)*this_ws->max_len; EDGE_ID orig_ptr = 0; EDGE_ID red_ptr = red_start_idx; EDGE_ID scratch_ptr = 0; while ((orig_ptr < this_ws->len) && (red_ptr < red_finish_idx)){ if (orig[orig_ptr] < self->g_R_sparse_H0[red_ptr]){ scratch[scratch_ptr++] = orig[orig_ptr++]; } else if (orig[orig_ptr] > self->g_R_sparse_H0[red_ptr]){ scratch[scratch_ptr++] = self->g_R_sparse_H0[red_ptr++]; } else{ orig_ptr++; red_ptr++; } } while (orig_ptr < this_ws->len){ scratch[scratch_ptr++] = orig[orig_ptr++]; } while (red_ptr < red_finish_idx){ scratch[scratch_ptr++] = self->g_R_sparse_H0[red_ptr++]; } this_ws->len = scratch_ptr; if (!this_ws->len){ //idx = self->g_n_reduced_simplex[self->g_dim_now]; //idx = -1; break; } else{ this_ws->original = 1 - this_ws->original; orig = self->g_R_ws_H0[ws_counter] + this_ws->original*this_ws->max_len; this_ws->pivot = orig[this_ws->len-1]; idx = self->g_pivots_H0[this_ws->pivot]; } } } pthread_mutex_lock(&(self->g_thread_lock)); self->g_processed_threads++; } } void allocate_jobs(filtration* self, int ws_size){ int x = (int)(ws_size/self->g_cpu_count); int y = (ws_size % self->g_cpu_count); self->g_jobs[0] = 0; for (int i = 1; i < self->g_cpu_count+1; i++){ if (i < y + 1) self->g_jobs[i] = self->g_jobs[i-1] + x + 1; else self->g_jobs[i] = self->g_jobs[i-1] + x; } } void reduce_ws_H0(filtration* self){ //if (self->g_n_reduced_simplex_H0 > 0){ self->g_processed_threads = 0; pthread_cond_broadcast(&(self->g_start_workers)); while (self->g_processed_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ ,&(self->g_thread_lock)); } //} reduce_with_self_H0( \ self \ ); int count_valid = 0; for (int ws_counter=0; ws_counter < self->g_ws_counter; ws_counter++){ if (!self->g_R_ws_H0_info[ws_counter].len){continue;} if (self->g_R_ws_H0_info[ws_counter].flag_append_to_complex){ update_R_H0(self \ , ws_counter ); continue; } // Swap R EDGE_ID* temp = self->g_R_ws_H0[count_valid]; self->g_R_ws_H0[count_valid] = self->g_R_ws_H0[ws_counter]; self->g_R_ws_H0[ws_counter] = temp; // Swap R info boundary_H0_ws temp2 = self->g_R_ws_H0_info[count_valid]; self->g_R_ws_H0_info[count_valid] = self->g_R_ws_H0_info[ws_counter]; self->g_R_ws_H0_info[ws_counter] = temp2; // At this point, this has to be a non-zero column self->g_R_ws_H0_info[count_valid].flag_non_empty = 1; count_valid += 1; } self->g_ws_counter = count_valid; //if (dim) // self->g_H0_MAX = self->g_n_reduced_simplex[dim]; } void reduce_with_self_H0( \ filtration* self \ ){ int m; EDGE_ID orig_ptr, scratch_ptr, m_ptr, idx; EDGE_ID *orig, *scratch, *original_m; for (int ws_counter=0; ws_counter < self->g_ws_counter; ws_counter++){ boundary_H0_ws* this_ws = self->g_R_ws_H0_info + ws_counter; // If the simplex has already been reduced to 0 // then continue if (!this_ws->len){ this_ws->flag_append_to_complex = 0; continue; } m = 0; while (m < ws_counter){ boundary_H0_ws* m_ws = self->g_R_ws_H0_info + m; if (!m_ws->len){ m++; continue; } if (m_ws->pivot > this_ws->pivot){ if (m_ws->flag_red_w_complex){ this_ws->flag_append_to_complex = 0; break; } m++; continue; } if (m_ws->pivot < this_ws->pivot){ m++; continue; } if (!m_ws->flag_append_to_complex){ m++; continue; } orig = self->g_R_ws_H0[ws_counter] + this_ws->original*this_ws->max_len; if ((this_ws->len + m_ws->len) > this_ws->max_len){ if (this_ws->original){ for (EDGE_ID it = 0; it < this_ws->len; it++){ orig[it] = orig[it + this_ws->max_len]; } this_ws->original = 0; } this_ws->max_len = this_ws->len + m_ws->len + 100; self->g_R_ws_H0[ws_counter] = (EDGE_ID*)realloc(self->g_R_ws_H0[ws_counter]\ , 2*this_ws->max_len*sizeof(EDGE_ID)); orig = self->g_R_ws_H0[ws_counter]; } scratch = self->g_R_ws_H0[ws_counter] + (1-this_ws->original)*this_ws->max_len; original_m = self->g_R_ws_H0[m] + m_ws->original*m_ws->max_len; // Store the result in scratch orig_ptr = 0; scratch_ptr = 0; m_ptr = 0; while ((orig_ptr < this_ws->len) && (m_ptr < m_ws->len)){ if (orig[orig_ptr] < original_m[m_ptr]){ scratch[scratch_ptr++] = orig[orig_ptr++]; } else if (orig[orig_ptr] > original_m[m_ptr]){ scratch[scratch_ptr++] = original_m[m_ptr++]; } else{ orig_ptr++; m_ptr++; } } while (orig_ptr < this_ws->len){ scratch[scratch_ptr++] = orig[orig_ptr++]; } while (m_ptr < m_ws->len){ scratch[scratch_ptr++] = original_m[m_ptr++]; } this_ws->len = scratch_ptr; if (!scratch_ptr){ this_ws->flag_append_to_complex = 0; break; } this_ws->pivot = scratch[scratch_ptr - 1]; this_ws->original = 1 - this_ws->original; //if (self->g_n_reduced_simplex_H0){ idx = self->g_pivots_H0[this_ws->pivot]; // If the pivot is in red complex, then this has to be reduced w/ complex //if (idx != self->g_n_reduced_simplex[self->g_dim_now]){ if (idx){ this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; break; } //} m = 0; }//End of m loop } }//End of red_ws_w_self_single void update_R_H0(filtration* self, int ws_counter){ boundary_H0_ws* this_ws = self->g_R_ws_H0_info + ws_counter; EDGE_ID* orig = self->g_R_ws_H0[ws_counter] + this_ws->original*this_ws->max_len; // Check space for R Sparse if ((this_ws->len + self->g_R_sparse_ptr_H0) > self->g_R_sparse_max_H0 ){ self->g_R_sparse_max_H0 = this_ws->len + self->g_R_sparse_ptr_H0 + 1000; self->g_R_sparse_H0 = (EDGE_ID*)realloc(self->g_R_sparse_H0\ , self->g_R_sparse_max_H0*sizeof(EDGE_ID)); } // Check space for R col indices if ((self->g_R_col_indices_ptr_H0 + 3) > self->g_R_col_indices_max_H0){ self->g_R_col_indices_max_H0 += 100; self->g_R_col_indices_H0 = (EDGE_ID*)realloc(self->g_R_col_indices_H0\ , self->g_R_col_indices_max_H0*sizeof(EDGE_ID)); } self->g_pivots_H0[this_ws->pivot] = self->g_R_col_indices_ptr_H0; self->g_R_col_indices_H0[self->g_R_col_indices_ptr_H0++] = self->g_R_sparse_ptr_H0; for (EDGE_ID j=0; j < this_ws->len; j++){ self->g_R_sparse_H0[self->g_R_sparse_ptr_H0++] = orig[j]; } self->g_R_col_indices_H0[self->g_R_col_indices_ptr_H0++] = self->g_R_sparse_ptr_H0; // Update edges with pivots for H0 to be used in clearing algo self->g_edges_with_pivots_H0[this_ws->cob] = 1; //#ifdef HOM_CYCLES // Update vertex in pivot to edge mapping if (self->g_compute_cycles){ self->g_H0_pivot_of[this_ws->pivot].coface = this_ws->cob; } //#endif } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(PAR* arr, EDGE_ID* aux, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ PAR *L, *R; L = (PAR*)malloc(n1*sizeof(PAR)); R = (PAR*)malloc(n2*sizeof(PAR)); /* create temp arrays */ EDGE_ID* L_aux; EDGE_ID* R_aux; L_aux = (EDGE_ID*)malloc(2*n1*sizeof(EDGE_ID)); R_aux = (EDGE_ID*)malloc(2*n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; L_aux[2*i] = aux[2*(l + i)]; L_aux[2*i+1] = aux[2*(l + i) + 1]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; R_aux[2*j] = aux[2*(m + 1+ j)]; R_aux[2*j+1] = aux[2*(m + 1+ j)+1]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; aux[2*k] = L_aux[2*i]; aux[2*k+1] = L_aux[2*i+1]; i++; } else { arr[k] = R[j]; aux[2*k] = R_aux[2*j]; aux[2*k+1] = R_aux[2*j+1]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; aux[2*k] = L_aux[2*i]; aux[2*k+1] = L_aux[2*i+1]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; aux[2*k] = R_aux[2*j]; aux[2*k+1] = R_aux[2*j+1]; j++; k++; } free(L); free(R); free(L_aux); free(R_aux); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(PAR* arr, EDGE_ID* aux, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort(arr, aux, l, m); mergeSort(arr, aux, m+1, r); merge(arr, aux, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR V_H0 ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_V_H0(EDGE_ID* arr, EDGE_ID** aux, EDGE_ID* aux2, EDGE_ID* aux3, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ EDGE_ID *L, *R; L = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); /* create temp arrays */ EDGE_ID** L_aux; EDGE_ID** R_aux; L_aux = (EDGE_ID**)malloc(n1*sizeof(EDGE_ID*)); R_aux = (EDGE_ID**)malloc(n2*sizeof(EDGE_ID*)); /* create temp arrays */ EDGE_ID* L_aux2; EDGE_ID* R_aux2; L_aux2 = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R_aux2 = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); /* create temp arrays */ EDGE_ID* L_aux3; EDGE_ID* R_aux3; L_aux3 = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R_aux3 = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; L_aux[i] = aux[l + i]; L_aux2[i] = aux2[l + i]; L_aux3[i] = aux3[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; R_aux[j] = aux[m + 1+ j]; R_aux2[j] = aux2[m + 1+ j]; R_aux3[j] = aux3[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; aux[k] = L_aux[i]; aux2[k] = L_aux2[i]; aux3[k] = L_aux3[i]; i++; } else { arr[k] = R[j]; aux[k] = R_aux[j]; aux2[k] = R_aux2[j]; aux3[k] = R_aux3[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; aux[k] = L_aux[i]; aux2[k] = L_aux2[i]; aux3[k] = L_aux3[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; aux[k] = R_aux[j]; aux2[k] = R_aux2[j]; aux3[k] = R_aux3[j]; j++; k++; } free(L); free(R); free(L_aux); free(R_aux); free(L_aux2); free(R_aux2); free(L_aux3); free(R_aux3); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_V_H0(EDGE_ID* arr, EDGE_ID** aux, EDGE_ID* aux2, EDGE_ID* aux3, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_V_H0(arr, aux, aux2, aux3, l, m); mergeSort_V_H0(arr, aux, aux2, aux3, m+1, r); merge_V_H0(arr, aux, aux2, aux3, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR V_H1 ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_V_H1(EDGE_ID* arr, simplex** aux, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ EDGE_ID *L, *R; L = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); /* create temp arrays */ simplex** L_aux; simplex** R_aux; L_aux = (simplex**)malloc(n1*sizeof(simplex*)); R_aux = (simplex**)malloc(n2*sizeof(simplex*)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; L_aux[i] = aux[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; R_aux[j] = aux[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; aux[k] = L_aux[i]; i++; } else { arr[k] = R[j]; aux[k] = R_aux[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; aux[k] = L_aux[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; aux[k] = R_aux[j]; j++; k++; } free(L); free(R); free(L_aux); free(R_aux); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_V_H1(EDGE_ID* arr, simplex** aux, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_V_H1(arr, aux, l, m); mergeSort_V_H1(arr, aux, m+1, r); merge_V_H1(arr, aux, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR Llen ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_Llen(EDGE_ID* arr, EDGE_ID* aux, EDGE_ID* aux2, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ EDGE_ID *L, *R; L = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); /* create temp arrays */ EDGE_ID *L_aux, *R_aux; L_aux = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R_aux = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); /* create temp arrays */ EDGE_ID *L_aux2, *R_aux2; L_aux2 = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R_aux2 = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; L_aux[i] = aux[l + i]; L_aux2[i] = aux2[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; R_aux[j] = aux[m + 1+ j]; R_aux2[j] = aux2[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; aux[k] = L_aux[i]; aux2[k] = L_aux2[i]; i++; } else { arr[k] = R[j]; aux[k] = R_aux[j]; aux2[k] = R_aux2[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; aux[k] = L_aux[i]; aux2[k] = L_aux2[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; aux[k] = R_aux[j]; aux2[k] = R_aux2[j]; j++; k++; } free(L); free(R); free(L_aux); free(R_aux); free(L_aux2); free(R_aux2); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_Llen(EDGE_ID* arr, EDGE_ID* aux, EDGE_ID* aux2, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_Llen(arr, aux, aux2, l, m); mergeSort_Llen(arr, aux, aux2, m+1, r); merge_Llen(arr, aux, aux2, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR temp_par ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_temp_par(PAR* arr, EDGE_ID* aux, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ PAR *L, *R; L = (PAR*)malloc(n1*sizeof(PAR)); R = (PAR*)malloc(n2*sizeof(PAR)); /* create aux arrays */ EDGE_ID *L_aux, *R_aux; L_aux = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R_aux = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; L_aux[i] = aux[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; R_aux[j] = aux[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; aux[k] = L_aux[i]; i++; } else { arr[k] = R[j]; aux[k] = R_aux[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; aux[k] = L_aux[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; aux[k] = R_aux[j]; j++; k++; } free(L); free(R); free(L_aux); free(R_aux); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_temp_par(PAR* arr, EDGE_ID* aux, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_temp_par(arr, aux, l, m); mergeSort_temp_par(arr, aux, m+1, r); merge_temp_par(arr, aux, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR in_cycles_len ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_incycleslen(EDGE_ID* arr, cyc_info* aux, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ EDGE_ID *L, *R; L = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (aux[L[i]].len <= aux[R[j]].len) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } free(L); free(R); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_incycleslen(EDGE_ID* arr, cyc_info* aux, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_incycleslen(arr, aux, l, m); mergeSort_incycleslen(arr, aux, m+1, r); merge_incycleslen(arr, aux, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR edges_in_cycles ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_edges_in_cycles(EDGE_ID* arr, cyc_info* aux, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ EDGE_ID *L, *R; L = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (aux[L[i]].len >= aux[R[j]].len) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } free(L); free(R); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_edges_in_cycles(EDGE_ID* arr, cyc_info* aux, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_edges_in_cycles(arr, aux, l, m); mergeSort_edges_in_cycles(arr, aux, m+1, r); merge_edges_in_cycles(arr, aux, l, m, r); } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR edges_in_cycles by cycid ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_edges_in_cycles_bycycid(EDGE_ID* arr, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ EDGE_ID *L, *R; L = (EDGE_ID*)malloc(n1*sizeof(EDGE_ID)); R = (EDGE_ID*)malloc(n2*sizeof(EDGE_ID)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } free(L); free(R); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_edges_in_cycles_bycycid(EDGE_ID* arr, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_edges_in_cycles_bycycid(arr, l, m); mergeSort_edges_in_cycles_bycycid(arr, m+1, r); merge_edges_in_cycles_bycycid(arr, l, m, r); } } #ifdef COMBIDX int H2_case1(filtration* self, coboundary_H2* V_info){ //if (self->g_p_flag){ // printf("\nstarting H2 case 1"); // getchar(); //} //EDGE_ID o_ab = V_info->triangle.key1; VERT_ID a = self->g_edges_list[2*V_info->triangle.key1]; VERT_ID b = self->g_edges_list[2*V_info->triangle.key1+1]; VERT_ID c = V_info->triangle.key2; VERT_ID idxa, idxb, idxc; while ((V_info->c_ptr < self->g_Neigh_len[c])\ && (self->g_Neighbors_e[c][V_info->c_ptr].order < V_info->triangle.key1)){ VERT_ID d = self->g_Neighbors_e[c][V_info->c_ptr].neighbor; if ((d == a) || (d == b)){ V_info->c_ptr++; continue; } if (COMB_IDX(a, d) > V_info->triangle.key1){ V_info->c_ptr++; continue; } if (COMB_IDX(b, d) > V_info->triangle.key1){ V_info->c_ptr++; continue; } V_info->low.key1 = V_info->triangle.key1; V_info->low.key2 = self->g_Neighbors_e[c][V_info->c_ptr].order; V_info->vertex = 0; return 1; } return 0; } void H2_case2 ( filtration* self, coboundary_H2* V_info){ //if (self->g_p_flag){ // printf("\nstarting H2 case 2"); // getchar(); //} VERT_ID idxa, idxb, idxc, idx; VERT_ID a, b, c; EDGE_ID o_ad, o_bd, o_cd; c = V_info->triangle.key2; a = self->g_edges_list[2*V_info->triangle.key1]; b = self->g_edges_list[2*V_info->triangle.key1+1]; while (1){ EDGE_ID ep = self->g_n_valid_edges; VERT_ID d; int flag = -1; if (V_info->a_ptr < self->g_Neigh_len[a]){ ep = self->g_Neighbors_e[a][V_info->a_ptr].order; flag = 1; } if (V_info->b_ptr < self->g_Neigh_len[b]){ if (self->g_Neighbors_e[b][V_info->b_ptr].order < ep){ ep = self->g_Neighbors_e[b][V_info->b_ptr].order; flag = 2; } } if (V_info->c_ptr < self->g_Neigh_len[c]){ if (self->g_Neighbors_e[c][V_info->c_ptr].order < ep){ ep = self->g_Neighbors_e[c][V_info->c_ptr].order; flag = 3; } } if (flag == -1){ V_info->low.key1 = ep; V_info->vertex = -1; return; } else if (flag == 1){ d = self->g_Neighbors_e[a][V_info->a_ptr].neighbor; if ((d == b) || (d == c)){ V_info->a_ptr++; continue; } o_bd = COMB_IDX(b, d); if (o_bd > ep){ V_info->a_ptr++; continue; } o_cd = COMB_IDX(c, d); if (o_cd > ep){ V_info->a_ptr++; continue; } V_info->low.key1 = ep; //o_bc = COMB_IDX(b, c); V_info->low.key2 = COMB_IDX(b, c); V_info->vertex = 1; return; } else if (flag == 2){ d = self->g_Neighbors_e[b][V_info->b_ptr].neighbor; if ((d == a) || (d == c)){ V_info->b_ptr++; continue; } o_ad = COMB_IDX(a, d); if (o_ad > ep){ V_info->b_ptr++; continue; } o_cd = COMB_IDX(c, d); if (o_cd > ep){ V_info->b_ptr++; continue; } V_info->low.key1 = ep; //o_ac = COMB_IDX(a, c); V_info->low.key2 = COMB_IDX(a, c); V_info->vertex = 2; return; } else if (flag == 3){ d = self->g_Neighbors_e[c][V_info->c_ptr].neighbor; if ((d == a) || (d == b)){ V_info->c_ptr++; continue; } o_ad = COMB_IDX(a, d); if (o_ad > ep){ V_info->c_ptr++; continue; } o_bd = COMB_IDX(b, d); if (o_bd > ep){ V_info->c_ptr++; continue; } V_info->low.key1 = ep; V_info->low.key2 = V_info->triangle.key1; V_info->vertex = 3; return; } } //V_info->low.key1 = self->g_n_valid_edges; //V_info->vertex = -1; } #else int H2_case1(filtration* self, coboundary_H2* V_info){ //if (self->g_p_flag){ // printf("\nstarting H2 case 1"); // getchar(); //} //EDGE_ID o_ab = V_info->triangle.key1; VERT_ID a = self->g_edges_list[2*V_info->triangle.key1]; VERT_ID b = self->g_edges_list[2*V_info->triangle.key1+1]; VERT_ID c = V_info->triangle.key2; VERT_ID idxa, idxb, idxc; while ((V_info->c_ptr < self->g_Neigh_len[c])\ && (self->g_Neighbors_e[c][V_info->c_ptr].order < V_info->triangle.key1)){ VERT_ID d = self->g_Neighbors_e[c][V_info->c_ptr].neighbor; idxa = search_Neighbors(self, a, d, 0, self->g_Neigh_len[a] - 1); if (idxa == self->g_n_vert){ V_info->c_ptr++; continue; } if (self->g_Neighbors[a][idxa].order > V_info->triangle.key1){ V_info->c_ptr++; continue; } idxb = search_Neighbors(self, b, d, 0, self->g_Neigh_len[b] - 1); if (idxb == self->g_n_vert){ V_info->c_ptr++; continue; } if (self->g_Neighbors[b][idxb].order > V_info->triangle.key1){ V_info->c_ptr++; continue; } V_info->low.key1 = V_info->triangle.key1; V_info->low.key2 = self->g_Neighbors_e[c][V_info->c_ptr].order; V_info->vertex = 0; return 1; } return 0; } void H2_case2 ( filtration* self, coboundary_H2* V_info){ //if (self->g_p_flag){ // printf("\nstarting H2 case 2"); // getchar(); //} VERT_ID idxa, idxb, idxc, idx; VERT_ID a, b, c; EDGE_ID o_ad, o_bd, o_cd; c = V_info->triangle.key2; a = self->g_edges_list[2*V_info->triangle.key1]; b = self->g_edges_list[2*V_info->triangle.key1+1]; while (1){ EDGE_ID ep = self->g_n_valid_edges; VERT_ID d; int flag = -1; if (V_info->a_ptr < self->g_Neigh_len[a]){ ep = self->g_Neighbors_e[a][V_info->a_ptr].order; flag = 1; } if (V_info->b_ptr < self->g_Neigh_len[b]){ if (self->g_Neighbors_e[b][V_info->b_ptr].order < ep){ ep = self->g_Neighbors_e[b][V_info->b_ptr].order; flag = 2; } } if (V_info->c_ptr < self->g_Neigh_len[c]){ if (self->g_Neighbors_e[c][V_info->c_ptr].order < ep){ ep = self->g_Neighbors_e[c][V_info->c_ptr].order; flag = 3; } } if (flag == -1){ V_info->low.key1 = ep; V_info->vertex = -1; return; } else if (flag == 1){ d = self->g_Neighbors_e[a][V_info->a_ptr].neighbor; idxb = search_Neighbors(self, b, d, 0, self->g_Neigh_len[b]-1); if (idxb == self->g_n_vert){ V_info->a_ptr++; continue; } o_bd = self->g_Neighbors[b][idxb].order; if (o_bd > ep){ V_info->a_ptr++; continue; } idxc = search_Neighbors(self, c, d, 0, self->g_Neigh_len[c]-1); if (idxc == self->g_n_vert){ V_info->a_ptr++; continue; } o_cd = self->g_Neighbors[c][idxc].order; if (o_cd > ep){ V_info->a_ptr++; continue; } V_info->low.key1 = ep; idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); V_info->low.key2 = self->g_Neighbors[b][idx].order; V_info->vertex = 1; return; } else if (flag == 2){ d = self->g_Neighbors_e[b][V_info->b_ptr].neighbor; idxa = search_Neighbors(self, a, d, 0, self->g_Neigh_len[a]-1); if (idxa == self->g_n_vert){ V_info->b_ptr++; continue; } o_ad = self->g_Neighbors[a][idxa].order; if (o_ad > ep){ V_info->b_ptr++; continue; } idxc = search_Neighbors(self, c, d, 0, self->g_Neigh_len[c]-1); if (idxc == self->g_n_vert){ V_info->b_ptr++; continue; } o_cd = self->g_Neighbors[c][idxc].order; if (o_cd > ep){ V_info->b_ptr++; continue; } V_info->low.key1 = ep; idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); V_info->low.key2 = self->g_Neighbors[a][idx].order; V_info->vertex = 2; return; } else if (flag == 3){ d = self->g_Neighbors_e[c][V_info->c_ptr].neighbor; idxb = search_Neighbors(self, b, d, 0, self->g_Neigh_len[b]-1); if (idxb == self->g_n_vert){ V_info->c_ptr++; continue; } o_bd = self->g_Neighbors[b][idxb].order; if (o_bd > ep){ V_info->c_ptr++; continue; } idxa = search_Neighbors(self, a, d, 0, self->g_Neigh_len[a]-1); if (idxa == self->g_n_vert){ V_info->c_ptr++; continue; } o_ad = self->g_Neighbors[a][idxa].order; if (o_ad > ep){ V_info->c_ptr++; continue; } V_info->low.key1 = ep; //idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); V_info->low.key2 = V_info->triangle.key1; V_info->vertex = 3; return; } } //V_info->low.key1 = self->g_n_valid_edges; //V_info->vertex = -1; } #endif void update_V_coH1(filtration* self, int ws_counter){ EDGE_ID red_col = 0; coboundary_H1_ws* this_ws = self->g_V_ws_H1 + ws_counter; //if (self->g_new_debug){ // // printf("\n ADDDDDING %d, %d, %d", this_ws->edge\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); // getchar(); //} //printf("\n%d, %d, %d", this_ws->edge\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); self->g_V_sparse_beg_ptr = self->g_V_sparse_ptr; if (this_ws->v_edges.last){ if ((this_ws->v_edges.last + self->g_V_sparse_ptr) + 1 > self->g_V_sparse_max){ self->g_V_sparse_max = self->g_V_sparse_ptr + this_ws->v_edges.last + 10000; self->g_V_sparse_H1 = (EDGE_ID*)realloc(self->g_V_sparse_H1\ , self->g_V_sparse_max*sizeof(EDGE_ID)); } if (this_ws->v_edges.last > 1){ #ifdef VREDUCE1 sorter8_tim_sort(this_ws->v_edges.o_ab, this_ws->v_edges.last); int coeff = 1; for (EDGE_ID vv = 0; vv < this_ws->v_edges.last-1; vv++){ if (this_ws->v_edges.o_ab[vv] == this_ws->v_edges.o_ab[vv+1]) { coeff = 1 - coeff; } else{ if (coeff){ self->g_V_sparse_H1[self->g_V_sparse_ptr++] = this_ws->v_edges.o_ab[vv]; } coeff = 1; } } if (coeff){ self->g_V_sparse_H1[self->g_V_sparse_ptr++] = this_ws->v_edges.o_ab[this_ws->v_edges.last-1]; } #else for (EDGE_ID vv = 0; vv < this_ws->v_edges.last; vv++){ self->g_V_sparse_H1[self->g_V_sparse_ptr++] = this_ws->v_edges.o_ab[vv]; } #endif } else if (this_ws->v_edges.last == 1){ self->g_V_sparse_H1[self->g_V_sparse_ptr++] = this_ws->v_edges.o_ab[0]; } //if (this_ws->edge == self->g_debug_edge){ // printf("\nAfter adding to V sparse "); // for (EDGE_ID bb = self->g_V_sparse_beg_ptr; bb < self->g_V_sparse_ptr; bb++){ // printf("%d, ", self->g_V_sparse_H1[bb]); // } // getchar(); //} // All have been added this_ws->v_edges.last = 0; if ((self->g_V_sparse_ptr - self->g_V_sparse_beg_ptr) > 0){ red_col = self->g_V_col_indices_ptr; if (self->g_V_col_indices_ptr+1 == self->g_V_col_indices_max){ self->g_V_col_indices_max += 1000; self->g_V_col_indices = (EDGE_ID*)realloc(self->g_V_col_indices , self->g_V_col_indices_max*sizeof(EDGE_ID)); } self->g_V_col_indices[self->g_V_col_indices_ptr] = self->g_V_sparse_beg_ptr; self->g_V_col_indices[self->g_V_col_indices_ptr+1] = self->g_V_sparse_ptr; self->g_V_col_indices_ptr++; } } #ifdef COH1DEBUG if (this_ws->edge == self->g_debug_edge){ printf("\n%d, %d, %d, %d: "\ , this_ws->pivot.key1\ , this_ws->pivot.key2\ , this_ws->edge\ , self->g_V_sparse_ptr - self->g_V_sparse_beg_ptr\ ); for (EDGE_ID mm = self->g_V_sparse_beg_ptr; mm < self->g_V_sparse_ptr; mm++){ printf("%d, ", self->g_V_sparse_H1[mm]); } getchar(); } #endif #ifdef VDEBUG if (self->g_V_sparse_ptr - self->g_V_sparse_beg_ptr > 0){ printf("\n%d, %d, %d, %d"\ , this_ws->pivot.key1\ , this_ws->pivot.key2\ , this_ws->edge\ , self->g_V_sparse_ptr - self->g_V_sparse_beg_ptr\ ); //getchar(); } #endif // ADDING THE LOW if (!self->g_H1_cohom_pivots_max_len[this_ws->pivot.key1]){ self->g_H1_cohom_pivots_max_len[this_ws->pivot.key1] = 2; self->g_H1_cohom_pivots[this_ws->pivot.key1] = \ (H1_cohom_pivots*)malloc(self->g_H1_cohom_pivots_max_len[this_ws->pivot.key1]*sizeof(H1_cohom_pivots)); } if (self->g_H1_cohom_pivots_len[this_ws->pivot.key1]\ == self->g_H1_cohom_pivots_max_len[this_ws->pivot.key1]){ self->g_H1_cohom_pivots_max_len[this_ws->pivot.key1] += 5; self->g_H1_cohom_pivots[this_ws->pivot.key1] = (H1_cohom_pivots*)realloc( \ self->g_H1_cohom_pivots[this_ws->pivot.key1] \ , self->g_H1_cohom_pivots_max_len[this_ws->pivot.key1]*sizeof(H1_cohom_pivots)); //self->g_cohom_ALL_pivots_len += 5; } EDGE_ID old_ptr = self->g_H1_cohom_pivots_len[this_ws->pivot.key1]; EDGE_ID new_ptr = self->g_H1_cohom_pivots_len[this_ws->pivot.key1]; while (old_ptr){ old_ptr--; if (self->g_H1_cohom_pivots[this_ws->pivot.key1][old_ptr].key2 > this_ws->pivot.key2){ self->g_H1_cohom_pivots[this_ws->pivot.key1][new_ptr--] =\ self->g_H1_cohom_pivots[this_ws->pivot.key1][old_ptr]; continue; } break; } //printf("\nAdding pivot (%d, %d) for edge %d"\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // , this_ws->edge\ // ); self->g_H1_cohom_pivots[this_ws->pivot.key1][new_ptr].key2 = this_ws->pivot.key2; self->g_H1_cohom_pivots[this_ws->pivot.key1][new_ptr].col_idx = red_col; self->g_H1_cohom_pivots[this_ws->pivot.key1][new_ptr].bndry = this_ws->edge; self->g_H1_cohom_pivots_len[this_ws->pivot.key1]++; // PERS PAIRS // Add non-zero barcodes PAR birth = self->g_edge_parameter[this_ws->edge]; PAR death = self->g_edge_parameter[this_ws->pivot.key1]; if (birth != death){ //printf("\nNon trivial pers pair (%f, %f)", birth, death); #ifdef DEBUGPIVOTS printf("\nBirth, death (%lf, %lf)", birth, death); printf("\n%d at pair (%d, %d)", this_ws->edge\ , this_ws->pivot.key1\ , this_ws->pivot.key2); getchar(); #endif //if (birth > death){ // //} if (self->g_H1_pers_pairs_len+2 == self->g_H1_pers_pairs_max_len){ self->g_H1_pers_pairs_max_len += 1000; self->g_H1_pers_pairs = (PAR*)realloc(self->g_H1_pers_pairs\ , self->g_H1_pers_pairs_max_len*sizeof(PAR)); } self->g_H1_pers_pairs[self->g_H1_pers_pairs_len++] = birth; self->g_H1_pers_pairs[self->g_H1_pers_pairs_len++] = death; } } void deallocator(filtration* self){ struct timespec start_wall_clock; struct timespec finish_wall_clock; double timer; if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); } free(self->filename); //free(self->g_homH1_cycles_file); // Deallocate edges free(self->g_edge_parameter); free(self->g_edges_list); for (EDGE_ID mm = 0; mm < self->g_n_valid_edges; mm++){ if (self->g_dim_lim > 0){ if (self->g_H1_cohom_pivots_max_len[mm]){ free(self->g_H1_cohom_pivots[mm]); } if (self->g_dim_lim > 1){ if (self->g_H2_cohom_pivots_max_len[mm]){ free(self->g_H2_cohom_pivots[mm]); } } } } // Deallocate Neighbors for (EDGE_ID mm = 0; mm < self->g_n_vert; mm++){ if (self->g_Neigh_len[mm]){ free(self->g_Neighbors[mm]); free(self->g_Neighbors_e[mm]); } } free(self->g_Neighbors); free(self->g_Neighbors_e); free(self->g_Neigh_len); // Deallocate R0 free(self->g_pivots_H0); free(self->g_R_sparse_H0); free(self->g_R_col_indices_H0); free(self->g_edges_with_pivots_H0); #ifdef SAVEPD free(self->g_H0_pers_file); #endif if (self->g_dim_lim > 0){ free(self->g_coH1_all_lows); free(self->g_H1_cohom_pivots); free(self->g_H1_cohom_pivots_len); free(self->g_H1_cohom_pivots_max_len); #ifdef SAVEPD free(self->g_H1_pers_file); #endif #ifdef SAVEV free(self->g_coH1_V_file); #endif free(self->g_H1_pers_pairs); free(self->g_V_col_indices); if (self->g_dim_lim > 1){ free(self->g_H2_cohom_pivots); free(self->g_H2_cohom_pivots_len); free(self->g_H2_cohom_pivots_max_len); #ifdef SAVEPD free(self->g_H2_pers_file); #endif #ifdef SAVEV free(self->g_coH2_V_file); #endif free(self->g_H2_pers_pairs); } } if (self->g_compute_cycles){ free(self->g_H1_undead); if (self->g_dim_lim > 1){ free(self->g_H2_undead); } } free(self); if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); timer = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); timer += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; printf("\nTime taken to deallocate: %lf", timer); } } void insert_in_implicit_v(filtration* self, int ws_counter, coboundary_H1* phi, int flag_next){ if (phi->low.key1 == self->g_n_valid_edges){ return; } coboundary_H1_ws* this_ws = self->g_V_ws_H1 + ws_counter; if (phi->low.key1 == this_ws->keys1[this_ws->k1_ptr].k1){ if (this_ws->keys1[this_ws->k1_ptr].last ==\ this_ws->keys1[this_ws->k1_ptr].max_len){ self->g_V_ws_H1[ws_counter].keys1[self->g_V_ws_H1[ws_counter].k1_ptr].max_len += 10; self->g_V_ws_H1[ws_counter].keys1[self->g_V_ws_H1[ws_counter].k1_ptr].keys2 = \ (implicit_keys2*)realloc\ (self->g_V_ws_H1[ws_counter].keys1[self->g_V_ws_H1[ws_counter].k1_ptr].keys2\ , self->g_V_ws_H1[ws_counter].keys1[self->g_V_ws_H1[ws_counter].k1_ptr].max_len\ *sizeof(implicit_keys2)); } EDGE_ID mm = this_ws->keys1[this_ws->k1_ptr].last; int compare; while (1){ //int compare = compare_implicit(this_ws->keys1[this_ws->k1_ptr].keys2[mm-1], *phi); if (this_ws->keys1[this_ws->k1_ptr].keys2[mm-1].k2 < phi->low.key2) compare = 0; else if (this_ws->keys1[this_ws->k1_ptr].keys2[mm-1].k2 > phi->low.key2) compare = 1; else{ if (this_ws->keys1[this_ws->k1_ptr].keys2[mm-1].o_ab < phi->o_ab) compare = 0; else compare = 1; } if (compare){ this_ws->keys1[this_ws->k1_ptr].keys2[mm] =\ this_ws->keys1[this_ws->k1_ptr].keys2[mm-1]; } else{ this_ws->keys1[this_ws->k1_ptr].keys2[mm].k2 = phi->low.key2; this_ws->keys1[this_ws->k1_ptr].keys2[mm].k2 = phi->low.key2; this_ws->keys1[this_ws->k1_ptr].keys2[mm].o_ab = phi->o_ab; this_ws->keys1[this_ws->k1_ptr].keys2[mm].a_ptr = phi->a_ptr; this_ws->keys1[this_ws->k1_ptr].keys2[mm].b_ptr = phi->b_ptr; this_ws->keys1[this_ws->k1_ptr].keys2[mm].flag_next = flag_next; this_ws->keys1[this_ws->k1_ptr].last++; return; } mm--; //// ERROR CHECKING, REMOVE LATER //if (!mm){ // printf("\nk2_ptr %d", v_implicit->k2_ptr); // printf("\nADDING %d:(%d, %d) to ", phi->o_ab, phi->low.key1, phi->low.key2); // print_v_implicit(self); // exit(0); // //} if (mm == this_ws->k2_ptr){ this_ws->keys1[this_ws->k1_ptr].keys2[mm].k2 = phi->low.key2; this_ws->keys1[this_ws->k1_ptr].keys2[mm].o_ab = phi->o_ab; this_ws->keys1[this_ws->k1_ptr].keys2[mm].a_ptr = phi->a_ptr; this_ws->keys1[this_ws->k1_ptr].keys2[mm].b_ptr = phi->b_ptr; this_ws->keys1[this_ws->k1_ptr].keys2[mm].flag_next = flag_next; this_ws->keys1[this_ws->k1_ptr].last++; return; } } } for (EDGE_ID mm = 0; mm < this_ws->last; mm++){ if (this_ws->keys1[mm].k1 == phi->low.key1){ //check_space_implicit_keys2(&(v_implicit->keys1[mm])); if (this_ws->keys1[mm].last ==\ this_ws->keys1[mm].max_len){ self->g_V_ws_H1[ws_counter].keys1[mm].max_len += 10; self->g_V_ws_H1[ws_counter].keys1[mm].keys2 = (implicit_keys2*)realloc\ (self->g_V_ws_H1[ws_counter].keys1[mm].keys2\ , self->g_V_ws_H1[ws_counter].keys1[mm].max_len*sizeof(implicit_keys2)); } this_ws->keys1[mm].flag_empty = 0; this_ws->keys1[mm].keys2[this_ws->keys1[mm].last].k2 = phi->low.key2; this_ws->keys1[mm].keys2[this_ws->keys1[mm].last].o_ab = phi->o_ab; this_ws->keys1[mm].keys2[this_ws->keys1[mm].last].a_ptr = phi->a_ptr; this_ws->keys1[mm].keys2[this_ws->keys1[mm].last].b_ptr = phi->b_ptr; this_ws->keys1[mm].keys2[this_ws->keys1[mm].last].flag_next = flag_next; this_ws->keys1[mm].last++; return; } } //if (self->g_new_debug){ // printf("\nBefore inserting c4"); // print_v_implicit(self); // getchar(); //} //check_space_implicit_keys1(v_implicit); if (self->g_V_ws_H1[ws_counter].last == self->g_V_ws_H1[ws_counter].max_len){ EDGE_ID mm = self->g_V_ws_H1[ws_counter].max_len; self->g_V_ws_H1[ws_counter].max_len += 10; self->g_V_ws_H1[ws_counter].keys1 = (implicit_keys1*)realloc(self->g_V_ws_H1[ws_counter].keys1\ , self->g_V_ws_H1[ws_counter].max_len*sizeof(implicit_keys1)); while (mm < self->g_V_ws_H1[ws_counter].max_len){ this_ws->keys1[mm].flag_empty = 1; this_ws->keys1[mm].max_len = 10; this_ws->keys1[mm].last = 0; self->g_V_ws_H1[ws_counter].keys1[mm].keys2 = (implicit_keys2*)malloc(10*sizeof(implicit_keys2)); mm++; } } this_ws->keys1[this_ws->last].flag_empty = 0; this_ws->keys1[this_ws->last].k1 = phi->low.key1; this_ws->keys1[this_ws->last].keys2[0].k2 = phi->low.key2; this_ws->keys1[this_ws->last].keys2[0].o_ab = phi->o_ab; this_ws->keys1[this_ws->last].keys2[0].a_ptr = phi->a_ptr; this_ws->keys1[this_ws->last].keys2[0].b_ptr = phi->b_ptr; this_ws->keys1[this_ws->last].keys2[0].flag_next = flag_next; this_ws->keys1[this_ws->last].last = 1; this_ws->last++; return; } void print_v_implicit(filtration* self, int ws_counter){ if (self->g_V_ws_H1[ws_counter].edge == self->g_debug_edge){ EDGE_ID k1_ptr = 0; if (k1_ptr == self->g_V_ws_H1[ws_counter].last){ printf("\nv implicit is empty"); return; } //EDGE_ID k2_ptr = self->g_v_implicit.k2_ptr; EDGE_ID k2_ptr = 0; while (k1_ptr < self->g_V_ws_H1[ws_counter].last){ //printf("\n%d, %d, last %d, flag_e %d ", k1_ptr\ // , self->g_v_implicit.keys1[k1_ptr].k1\ // , self->g_v_implicit.keys1[k1_ptr].last\ // , self->g_v_implicit.keys1[k1_ptr].flag_empty\ // ); if (self->g_V_ws_H1[ws_counter].keys1[k1_ptr].flag_empty){ printf("empty", k1_ptr, self->g_V_ws_H1[ws_counter].keys1[k1_ptr].k1); k1_ptr++; continue; } //if (k1_ptr == self->g_v_implicit.k1_ptr){ // printf("\nk1_ptr is %d, k2_ptr is %d", self->g_v_implicit.k1_ptr\ // , self->g_v_implicit.k2_ptr); //} //printf("\nentries in %d are %d", k1_ptr, self->g_v_implicit.keys1[k1_ptr].last); printf("\n"); printf("idx %d, last %d:: ", k1_ptr, self->g_V_ws_H1[ws_counter].keys1[k1_ptr].last); while (k2_ptr < self->g_V_ws_H1[ws_counter].keys1[k1_ptr].last){ printf("%d:(%d, %d):%d, ", self->g_V_ws_H1[ws_counter].keys1[k1_ptr].keys2[k2_ptr].o_ab\ , self->g_V_ws_H1[ws_counter].keys1[k1_ptr].k1\ , self->g_V_ws_H1[ws_counter].keys1[k1_ptr].keys2[k2_ptr].k2\ , self->g_V_ws_H1[ws_counter].keys1[k1_ptr].keys2[k2_ptr].flag_next\ ); k2_ptr++; } k2_ptr = 0; k1_ptr++; } } } void coH2_print_v_implicit(filtration* self, int ws_counter){ printf("\nk1ptr is %d, k2ptr is %d", self->g_V_ws_H2[ws_counter].k1_ptr\ , self->g_V_ws_H2[ws_counter].k2_ptr); EDGE_ID k1_ptr = 0; if (k1_ptr == self->g_V_ws_H2[ws_counter].last){ printf("\nv implicit is empty"); return; } //EDGE_ID k2_ptr = self->g_v_implicit.k2_ptr; EDGE_ID k2_ptr = 0; while (k1_ptr < self->g_V_ws_H2[ws_counter].last){ //printf("\n%d, %d, last %d, flag_e %d ", k1_ptr\ // , self->g_v_implicit.keys1[k1_ptr].k1\ // , self->g_v_implicit.keys1[k1_ptr].last\ // , self->g_v_implicit.keys1[k1_ptr].flag_empty\ // ); if (self->g_V_ws_H2[ws_counter].keys1[k1_ptr].flag_empty){ printf("empty", k1_ptr, self->g_V_ws_H2[ws_counter].keys1[k1_ptr].k1); k1_ptr++; continue; } //if (k1_ptr == self->g_v_implicit.k1_ptr){ // printf("\nk1_ptr is %d, k2_ptr is %d", self->g_v_implicit.k1_ptr\ // , self->g_v_implicit.k2_ptr); //} //printf("\nentries in %d are %d", k1_ptr, self->g_v_implicit.keys1[k1_ptr].last); printf("\n"); printf("idx %d, last %d:: ", k1_ptr, self->g_V_ws_H2[ws_counter].keys1[k1_ptr].last); while (k2_ptr < self->g_V_ws_H2[ws_counter].keys1[k1_ptr].last){ printf("(%d, %d):%d, "\ , self->g_V_ws_H2[ws_counter].keys1[k1_ptr].keys2[k2_ptr].o_abc.key1\ , self->g_V_ws_H2[ws_counter].keys1[k1_ptr].keys2[k2_ptr].o_abc.key2\ , self->g_V_ws_H2[ws_counter].keys1[k1_ptr].keys2[k2_ptr].flag_next\ ); k2_ptr++; } k2_ptr = 0; k1_ptr++; //, self->g_V_ws_H2[ws_counter].keys1[k1_ptr].k1\ //, self->g_V_ws_H2[ws_counter].keys1[k1_ptr].keys2[k2_ptr].k2\ } } void* reduce_with_complex_coH1(void* arg){ filtration* self = arg; pthread_mutex_lock(&(self->g_thread_lock)); int tid = ++self->g_thread_id; pthread_mutex_unlock(&(self->g_thread_lock)); for (;;){ pthread_mutex_lock(&(self->g_thread_lock)); self->g_sleeping_threads++; self->g_processed_threads++; if (self->g_sleeping_threads == self->g_cpu_count){ pthread_cond_signal(&(self->g_start_boss)); } pthread_cond_wait(&(self->g_start_workers), &(self->g_thread_lock)); if (self->g_delete_threads){ pthread_mutex_unlock(&(self->g_thread_lock)); pthread_exit(NULL); } self->g_sleeping_threads--; pthread_mutex_unlock(&(self->g_thread_lock)); for (int ws_counter = self->g_jobs[tid - 1]; ws_counter < self->g_jobs[tid]; ws_counter++){ coboundary_H1_ws* this_ws = self->g_V_ws_H1 + ws_counter; if (!this_ws->flag_non_empty){ // We are sure that we will exit only if there is no reduction // required with existing complex or with trivial pair this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 0; continue; } if (this_ws->flag_append_to_complex){ continue; } // If being processed for the first time... if (this_ws->flag_first){ this_ws->flag_first = 0; if ((self->g_coH1_all_lows[this_ws->pivot.key1].low.key1 == this_ws->pivot.key1)\ && (self->g_coH1_all_lows[this_ws->pivot.key1].low.key2 == this_ws->pivot.key2)){ this_ws->reduce_w_bndry = this_ws->pivot.key1; this_ws->V_col_idx = 0; this_ws->flag_red_w_trivial = 1; } else{ // If this low is not a pivot if (!self->g_H1_cohom_pivots_len[this_ws->pivot.key1]){ #ifdef COH1DEBUG if (this_ws->edge == self->g_debug_edge ){ printf("\n(%d, %d) pivot of %d is not a pivot 1"\ , this_ws->pivot.key1\ , this_ws->pivot.key2\ , this_ws->edge\ ); } #endif this_ws->flag_append_to_complex = 1; continue; } else{ EDGE_ID idx = search_H1_cohom_pivots(self->g_H1_cohom_pivots[this_ws->pivot.key1]\ , 0 \ , self->g_H1_cohom_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges); // If this low is not a pivot if (idx == self->g_n_valid_edges){ #ifdef COH1DEBUG if (this_ws->edge == self->g_debug_edge ){ printf("\n(%d, %d) pivot of %d is not a pivot 2"\ , this_ws->pivot.key1\ , this_ws->pivot.key2\ , this_ws->edge\ ); } #endif this_ws->flag_append_to_complex = 1; continue; } else{ this_ws->flag_red_w_complex = 1; this_ws->reduce_w_bndry = self->g_H1_cohom_pivots[this_ws->pivot.key1][idx].bndry; this_ws->V_col_idx = self->g_H1_cohom_pivots[this_ws->pivot.key1][idx].col_idx; } } } } if ((!this_ws->flag_red_w_trivial) && (!this_ws->flag_red_w_complex)){ this_ws->flag_append_to_complex = 1; continue; } // We know that parallel will end only when there are no more red. to be with trivial and complex this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 1; while(1){ EDGE_ID check_len = this_ws->v_edges.last + 1; if (this_ws->V_col_idx){ check_len += self->g_V_col_indices[this_ws->V_col_idx+1] -\ self->g_V_col_indices[this_ws->V_col_idx]; } if (check_len > this_ws->v_edges.max_len){ this_ws->v_edges.max_len = check_len + 100; self->g_V_ws_H1[ws_counter].v_edges.o_ab =\ (EDGE_ID*)realloc(self->g_V_ws_H1[ws_counter].v_edges.o_ab\ , this_ws->v_edges.max_len*sizeof(EDGE_ID)); } this_ws->v_edges.o_ab[this_ws->v_edges.last++] = this_ws->reduce_w_bndry; coboundary_H1 ttemp; ttemp.o_ab = this_ws->reduce_w_bndry; //if (this_ws->edge == self->g_debug_edge){ // printf("\n%d: Appending to v edge in parallel %d", this_ws->edge, ttemp.o_ab); // getchar(); //} find_H1_cohom_greater(self, &(ttemp), &(this_ws->pivot)); insert_in_implicit_v(self, ws_counter, &(ttemp), 1); // IF the V was recorded, add the bndries if (this_ws->V_col_idx){ // We have to cycle through the col in V and add all the other boundary columns for reduction EDGE_ID start = self->g_V_col_indices[this_ws->V_col_idx]; EDGE_ID end = self->g_V_col_indices[this_ws->V_col_idx+1]; for (EDGE_ID mm = start; mm < end; mm++){ this_ws->v_edges.o_ab[this_ws->v_edges.last++] = self->g_V_sparse_H1[mm]; ttemp.o_ab = self->g_V_sparse_H1[mm]; //if (this_ws->edge == self->g_debug_edge){ // printf(", %d", ttemp.o_ab); //} // Find the first low greater than or equal pivot find_H1_cohom_greater(self, &(ttemp), &(this_ws->pivot)); insert_in_implicit_v(self, ws_counter, &(ttemp), 1); } } //if (this_ws->edge == self->g_debug_edge){ // getchar(); //} reduce_hash_table_coH1(self, ws_counter); //if (this_ws->edge == self->g_debug_edge){ // printf("\nPivot after reduction in parallel is (%d, %d)", this_ws->pivot.key1\ // , this_ws->pivot.key2); //} if (!this_ws->flag_non_empty){ break; } // Check with trivial pair if ((self->g_coH1_all_lows[this_ws->pivot.key1].low.key1 == this_ws->pivot.key1)\ && (self->g_coH1_all_lows[this_ws->pivot.key1].low.key2 == this_ws->pivot.key2)){ this_ws->reduce_w_bndry = this_ws->pivot.key1; this_ws->V_col_idx = 0; continue; } // If this low is not a pivot if (!self->g_H1_cohom_pivots_len[this_ws->pivot.key1]){ break; } EDGE_ID idx = search_H1_cohom_pivots(self->g_H1_cohom_pivots[this_ws->pivot.key1]\ , 0 \ , self->g_H1_cohom_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges); if (idx == self->g_n_valid_edges){ break; } this_ws->reduce_w_bndry = self->g_H1_cohom_pivots[this_ws->pivot.key1][idx].bndry; this_ws->V_col_idx = self->g_H1_cohom_pivots[this_ws->pivot.key1][idx].col_idx; } } } } void reduce_with_self_coH1(filtration* self){ // Now we have to reduce for (int ws_counter = 0; ws_counter < self->g_ws_counter; ws_counter++){ coboundary_H1_ws* this_ws = self->g_V_ws_H1 + ws_counter; // If empty, then continue and don't append to complex if (!this_ws->flag_non_empty){ //this_ws->flag_append_to_complex = 0; continue; } int m = 0; // Keep reducing if reduce with complex flag is 0 and reduce with trivial flag is 0 while((m < ws_counter)\ && (!this_ws->flag_red_w_complex)\ && (!this_ws->flag_red_w_trivial)){ coboundary_H1_ws* m_ws = self->g_V_ws_H1 + m; // If m is empty, continue if (!m_ws->flag_non_empty){ m++; continue; } int compare; if (m_ws->pivot.key1 > this_ws->pivot.key1) compare = 1; else if (m_ws->pivot.key1 < this_ws->pivot.key1) compare = 0; else{ if (m_ws->pivot.key2 > this_ws->pivot.key2) compare = 1; else if (m_ws->pivot.key2 < this_ws->pivot.key2) compare = 0; else compare = -1; } // If pivot of m is higher than pivot of ws_counter // then we don't care if (compare == 1){ m++; continue; } // If pivot of m is lower than pivot of ws_counter // then if m has to be reduced, we have to hold ws_counter if (compare == 0){ if (m_ws->flag_red_w_complex || m_ws->flag_red_w_trivial){ this_ws->flag_append_to_complex = 0; break; } m++; continue; } // At this point they have same low if (m_ws->flag_red_w_complex || m_ws->flag_red_w_trivial){ this_ws->flag_append_to_complex = 0; //m++; break; //continue; } //printf("\nin serial reducing %d with %d", this_ws->edge, m_ws->edge); //getchar(); // Merge m and this_ws // // Merge v_edges if (this_ws->v_edges.last + m_ws->v_edges.last > this_ws->v_edges.max_len - 1){ this_ws->v_edges.max_len += m_ws->v_edges.last + 100; self->g_V_ws_H1[ws_counter].v_edges.o_ab = (EDGE_ID*)realloc(\ self->g_V_ws_H1[ws_counter].v_edges.o_ab\ , this_ws->v_edges.max_len*sizeof(EDGE_ID)); } // Add the original edge //if (this_ws->edge == self->g_debug_edge){ // printf("\nAdding to v edge in serial %d", m_ws->edge); //} this_ws->v_edges.o_ab[this_ws->v_edges.last++] = m_ws->edge; for (EDGE_ID bb = 0; bb < m_ws->v_edges.last; bb++){ //if (this_ws->edge == self->g_debug_edge){ // printf(", %d", m_ws->v_edges.o_ab[bb]); //} this_ws->v_edges.o_ab[this_ws->v_edges.last++] =\ m_ws->v_edges.o_ab[bb]; } // Merge hash tables coboundary_H1 ttemp; for (EDGE_ID bb = 0; bb < m_ws->last; bb++){ EDGE_ID m_start = 0; if (bb == m_ws->k1_ptr){ m_start = m_ws->k2_ptr; } ttemp.low.key1 = m_ws->keys1[bb].k1; for (EDGE_ID mm = m_start; mm < m_ws->keys1[bb].last; mm++){ ttemp.low.key2 = m_ws->keys1[bb].keys2[mm].k2; ttemp.o_ab = m_ws->keys1[bb].keys2[mm].o_ab; ttemp.a_ptr = m_ws->keys1[bb].keys2[mm].a_ptr; ttemp.b_ptr = m_ws->keys1[bb].keys2[mm].b_ptr; insert_in_implicit_v(self, ws_counter, &(ttemp)\ , m_ws->keys1[bb].keys2[mm].flag_next); } } // Now reduce reduce_hash_table_coH1(self, ws_counter); //if (this_ws->edge == self->g_debug_edge){ // printf("\nPivot after reduction in serial is (%d, %d)", this_ws->pivot.key1\ // , this_ws->pivot.key2); //} if (!this_ws->flag_non_empty){ break; } // Check with trivial pair if ((self->g_coH1_all_lows[this_ws->pivot.key1].low.key1 == this_ws->pivot.key1)\ && (self->g_coH1_all_lows[this_ws->pivot.key1].low.key2 == this_ws->pivot.key2)){ this_ws->flag_red_w_trivial = 1; this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 0; this_ws->reduce_w_bndry = this_ws->pivot.key1; this_ws->V_col_idx = 0; break; } // If this low is not a pivot if (self->g_H1_cohom_pivots_len[this_ws->pivot.key1]){ EDGE_ID idx = search_H1_cohom_pivots(self->g_H1_cohom_pivots[this_ws->pivot.key1]\ , 0 \ , self->g_H1_cohom_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges); if (idx != self->g_n_valid_edges){ this_ws->flag_red_w_trivial = 0; this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; this_ws->reduce_w_bndry = self->g_H1_cohom_pivots[this_ws->pivot.key1][idx].bndry; this_ws->V_col_idx = self->g_H1_cohom_pivots[this_ws->pivot.key1][idx].col_idx; break; } } // Reset m after single reduction m = 0; } } } void reduce_hash_table_coH1(filtration* self, int ws_counter){ // Now we have to reduce int coeff = 1; coboundary_H1_ws* this_ws = self->g_V_ws_H1 + ws_counter; coboundary_H1 ttemp; EDGE_ID* k1_ptr = &(this_ws->k1_ptr); EDGE_ID* k2_ptr = &(this_ws->k2_ptr); while (1){ if (this_ws->keys1[*k1_ptr].last == 1){ this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2 ==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].k2){ coeff = 1 - coeff; if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_ab ==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].o_ab){ if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].flag_next){ this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next = 0; this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].flag_next = 0; } } } else{ if (coeff){ this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } else{ coeff = 1; } } if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next){ ttemp.o_ab = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_ab; ttemp.a_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].a_ptr; ttemp.b_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].b_ptr; ttemp.low.key1 = this_ws->keys1[*k1_ptr].k1; ttemp.low.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; //if (this_ws->edge == self->g_debug_edge){ // printf("\nFinding next of %d:(%d, %d)", ttemp.o_ab\ // , ttemp.low.key1\ // , ttemp.low.key2\ // ); //} find_H1_cohom_next(self, &(ttemp)); this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next = 0; insert_in_implicit_v(self, ws_counter, &(ttemp), 1); // It is possible that last key1 and last key2 changed. Make sure last is consistent } *k2_ptr = *k2_ptr + 1; if (*k2_ptr == this_ws->keys1[*k1_ptr].last-1){ if (coeff){ this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next){ ttemp.o_ab = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_ab; ttemp.a_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].a_ptr; ttemp.b_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].b_ptr; ttemp.low.key1 = this_ws->keys1[*k1_ptr].k1; ttemp.low.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; //if (this_ws->edge == self->g_debug_edge){ // printf("\nFinding next of %d:(%d, %d)", ttemp.o_ab\ // , ttemp.low.key1\ // , ttemp.low.key2\ // ); //} find_H1_cohom_next(self, &(ttemp)); this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next = 0; insert_in_implicit_v(self, ws_counter, &(ttemp), 1); } if (*k2_ptr == this_ws->keys1[*k1_ptr].last-2){ *k2_ptr = *k2_ptr + 1; this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } else{ // Mark this key1 as empty this_ws->keys1[*k1_ptr].flag_empty = 1; // Reallocate to prune space if (this_ws->keys1[*k1_ptr].max_len > 5){ this_ws->keys1[*k1_ptr].max_len = 5; self->g_V_ws_H1[ws_counter].keys1[*k1_ptr].keys2 = \ (implicit_keys2*)realloc\ (self->g_V_ws_H1[ws_counter].keys1[*k1_ptr].keys2\ , self->g_V_ws_H1[ws_counter].keys1[*k1_ptr].max_len\ *sizeof(implicit_keys2)); } EDGE_ID current_ptr = 0; EDGE_ID minn = self->g_n_valid_edges; for (EDGE_ID mm = 0; mm < this_ws->last; mm++){ if (this_ws->keys1[mm].flag_empty){ continue; } implicit_keys1 ttemp = this_ws->keys1[current_ptr]; this_ws->keys1[current_ptr] = this_ws->keys1[mm]; this_ws->keys1[mm] = ttemp; if (this_ws->keys1[current_ptr].k1 < minn){ minn = this_ws->keys1[current_ptr].k1; *k1_ptr = current_ptr; } current_ptr++; } this_ws->last = current_ptr; if (minn == self->g_n_valid_edges){ this_ws->flag_non_empty = 0; break; } coeff = 1; *k2_ptr = 0; sorter7_tim_sort(this_ws->keys1[*k1_ptr].keys2\ , this_ws->keys1[*k1_ptr].last); } } } } void reduce_ws_coH1(filtration* self){ //printf("\nBefore parallel"); //for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ // printf("\n%d:(%d, %d) flag %d", self->g_V_ws_H1[mm].edge\ // , self->g_V_ws_H1[mm].pivot.key1\ // , self->g_V_ws_H1[mm].pivot.key2\ // , self->g_V_ws_H1[mm].flag_append_to_complex); // printf(" v: "); // for (EDGE_ID bb = 0; bb < self->g_V_ws_H1[mm].v_edges.last; bb++){ // printf("%d, ", self->g_V_ws_H1[mm].v_edges.o_ab[bb]); // } //} // // PARALLEL self->g_processed_threads = 0; pthread_cond_broadcast(&(self->g_start_workers)); while (self->g_processed_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ ,&(self->g_thread_lock)); } //printf("\nAfter parallel"); //for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ // printf("\n%d:(%d, %d) flag %d", self->g_V_ws_H1[mm].edge\ // , self->g_V_ws_H1[mm].pivot.key1\ // , self->g_V_ws_H1[mm].pivot.key2\ // , self->g_V_ws_H1[mm].flag_append_to_complex); // printf(" v: "); // for (EDGE_ID bb = 0; bb < self->g_V_ws_H1[mm].v_edges.last; bb++){ // printf("%d, ", self->g_V_ws_H1[mm].v_edges.o_ab[bb]); // } //} // SERIAL reduce_with_self_coH1(self); //printf("\nAfter serial"); //for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ // printf("\n%d:(%d, %d) flag %d", self->g_V_ws_H1[mm].edge\ // , self->g_V_ws_H1[mm].pivot.key1\ // , self->g_V_ws_H1[mm].pivot.key2\ // , self->g_V_ws_H1[mm].flag_append_to_complex); // printf(" v: "); // for (EDGE_ID bb = 0; bb < self->g_V_ws_H1[mm].v_edges.last; bb++){ // printf("%d, ", self->g_V_ws_H1[mm].v_edges.o_ab[bb]); // } //} //getchar(); // CLEARANCE int count_valid = 0; for (int ws_counter = 0; ws_counter < self->g_ws_counter; ws_counter++){ if (!self->g_V_ws_H1[ws_counter].flag_non_empty){ // Add the undead H1 if (self->g_H1_pers_pairs_len+2 == self->g_H1_pers_pairs_max_len){ self->g_H1_pers_pairs_max_len += 1000; self->g_H1_pers_pairs = (PAR*)realloc(self->g_H1_pers_pairs\ , self->g_H1_pers_pairs_max_len*sizeof(PAR)); } self->g_H1_pers_pairs[self->g_H1_pers_pairs_len++] = \ self->g_edge_parameter[self->g_V_ws_H1[ws_counter].edge]; self->g_H1_pers_pairs[self->g_H1_pers_pairs_len++] = -1; //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H1_undead[self->g_H1_undead_ptr++] = self->g_V_ws_H1[ws_counter].edge; if (self->g_H1_undead_ptr == self->g_H1_undead_max){ self->g_H1_undead_max += 100; self->g_H1_undead = (EDGE_ID*)realloc(self->g_H1_undead\ , self->g_H1_undead_max*sizeof(EDGE_ID)); } } //#endif continue; } if (self->g_V_ws_H1[ws_counter].flag_append_to_complex){ update_V_coH1(self, ws_counter); continue; } // Swap V coboundary_H1_ws temp = self->g_V_ws_H1[count_valid]; self->g_V_ws_H1[count_valid] = self->g_V_ws_H1[ws_counter]; self->g_V_ws_H1[ws_counter] = temp; // At this point, this has to be a non-zero column self->g_V_ws_H1[count_valid].flag_non_empty = 1; // Run through parallel at least once self->g_V_ws_H1[count_valid].flag_append_to_complex = 0; count_valid++; } self->g_ws_counter = count_valid; } void reduce_with_self_coH2(filtration* self){ // Now we have to reduce for (int ws_counter = 0; ws_counter < self->g_ws_counter; ws_counter++){ coboundary_H2_ws* this_ws = self->g_V_ws_H2 + ws_counter; // If empty, then continue and don't append to complex if (!this_ws->flag_non_empty){ //this_ws->flag_append_to_complex = 0; continue; } int m = 0; // Keep reducing if reduce with complex flag is 0 and reduce with trivial flag is 0 while((m < ws_counter)\ && (!this_ws->flag_red_w_complex)\ && (!this_ws->flag_red_w_trivial)){ coboundary_H2_ws* m_ws = self->g_V_ws_H2 + m; // If m is empty, continue if (!m_ws->flag_non_empty){ m++; continue; } int compare; if (m_ws->pivot.key1 > this_ws->pivot.key1) compare = 1; else if (m_ws->pivot.key1 < this_ws->pivot.key1) compare = 0; else{ if (m_ws->pivot.key2 > this_ws->pivot.key2) compare = 1; else if (m_ws->pivot.key2 < this_ws->pivot.key2) compare = 0; else compare = -1; } // If pivot of m is higher than pivot of ws_counter // then we don't care if (compare == 1){ m++; continue; } // If pivot of m is lower than pivot of ws_counter // then if m has to be reduced, we have to hold ws_counter if (compare == 0){ if (m_ws->flag_red_w_complex || m_ws->flag_red_w_trivial){ this_ws->flag_append_to_complex = 0; break; } m++; continue; } // At this point they have same low if (m_ws->flag_red_w_complex || m_ws->flag_red_w_trivial){ this_ws->flag_append_to_complex = 0; //m++; break; //continue; } //printf("\nin serial reducing %d with %d", this_ws->edge, m_ws->edge); //getchar(); // Merge m and this_ws // // Merge v_triangles if (this_ws->v_triangles.last + m_ws->v_triangles.last > this_ws->v_triangles.max_len - 1){ this_ws->v_triangles.max_len += m_ws->v_triangles.last + 100; self->g_V_ws_H2[ws_counter].v_triangles.o_abc = (simplex*)realloc(\ self->g_V_ws_H2[ws_counter].v_triangles.o_abc\ , this_ws->v_triangles.max_len*sizeof(simplex)); } // Add the original edge this_ws->v_triangles.o_abc[this_ws->v_triangles.last++] = m_ws->triangle; for (EDGE_ID bb = 0; bb < m_ws->v_triangles.last; bb++){ this_ws->v_triangles.o_abc[this_ws->v_triangles.last++] =\ m_ws->v_triangles.o_abc[bb]; } // Merge hash tables coboundary_H2 ttemp; for (EDGE_ID bb = 0; bb < m_ws->last; bb++){ EDGE_ID m_start = 0; if (bb == m_ws->k1_ptr){ m_start = m_ws->k2_ptr; } ttemp.low.key1 = m_ws->keys1[bb].k1; for (EDGE_ID mm = m_start; mm < m_ws->keys1[bb].last; mm++){ ttemp.low.key2 = m_ws->keys1[bb].keys2[mm].k2; ttemp.triangle = m_ws->keys1[bb].keys2[mm].o_abc; ttemp.a_ptr = m_ws->keys1[bb].keys2[mm].a_ptr; ttemp.b_ptr = m_ws->keys1[bb].keys2[mm].b_ptr; ttemp.c_ptr = m_ws->keys1[bb].keys2[mm].c_ptr; ttemp.vertex = m_ws->keys1[bb].keys2[mm].vertex; coH2_insert_in_implicit_v(self, ws_counter, &(ttemp)\ , m_ws->keys1[bb].keys2[mm].flag_next); } } // Now reduce reduce_hash_table_coH2(self, ws_counter); if (!this_ws->flag_non_empty){ break; } coboundary_H2 temptemp; // CHECK FOR TRIVIAL PAIR // Get low for maximum triangle <ab, d> in this_pivot temptemp.triangle.key1 = this_ws->pivot.key1; temptemp.triangle.key2 = self->g_edges_list[2*this_ws->pivot.key2+1]; find_H2_cohom_low(self, &temptemp); // Check if the low of this triangle is same as self->g_this_pivot if ((temptemp.low.key1 == this_ws->pivot.key1)\ && (temptemp.low.key2 == this_ws->pivot.key2)){ this_ws->flag_red_w_trivial = 1; this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 0; this_ws->reduce_w_bndry = temptemp.triangle; this_ws->V_col_idx = 0; break; } // If this low is not a pivot if (self->g_H2_cohom_pivots_len[this_ws->pivot.key1]){ EDGE_ID idx = search_H2_cohom_pivots(self->g_H2_cohom_pivots[this_ws->pivot.key1]\ , 0 \ , self->g_H2_cohom_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges); if (idx != self->g_n_valid_edges){ this_ws->flag_red_w_trivial = 0; this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; this_ws->reduce_w_bndry = self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].bndry; this_ws->V_col_idx = self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].col_idx; break; } } // Reset m after single reduction m = 0; } } } void* reduce_with_complex_coH2(void* arg){ filtration* self = arg; pthread_mutex_lock(&(self->g_thread_lock)); int tid = ++self->g_thread_id; coboundary_H2_ws* this_ws; coboundary_H2 temp; EDGE_ID idx, check_len, start, end; pthread_mutex_unlock(&(self->g_thread_lock)); for (;;){ pthread_mutex_lock(&(self->g_thread_lock)); self->g_sleeping_threads++; self->g_processed_threads++; if (self->g_sleeping_threads == self->g_cpu_count){ pthread_cond_signal(&(self->g_start_boss)); } pthread_cond_wait(&(self->g_start_workers), &(self->g_thread_lock)); if (self->g_delete_threads){ pthread_mutex_unlock(&(self->g_thread_lock)); pthread_exit(NULL); } self->g_sleeping_threads--; pthread_mutex_unlock(&(self->g_thread_lock)); for (int ws_counter = self->g_jobs[tid - 1]; ws_counter < self->g_jobs[tid]; ws_counter++){ this_ws = self->g_V_ws_H2 + ws_counter; //coboundary_H2 temp; //printf("\nProcessing (%d, %d)", this_ws->triangle.key1\ , this_ws->triangle.key2); if (!this_ws->flag_non_empty){ // We are sure that we will exit only if there is no reduction // required with existing complex or with trivial pair //printf("\nEmpty. Skipping."); this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 0; continue; } if (this_ws->flag_append_to_complex){ //printf("\nAppend to complex. Nothing to do."); continue; } if (this_ws->flag_first){ this_ws->flag_first = 0; // CHECK WITH TRIVIAL temp.triangle.key1 = this_ws->pivot.key1; temp.triangle.key2 = self->g_edges_list[2*this_ws->pivot.key2+1]; find_H2_cohom_low(self, &temp); if ((temp.low.key1 == this_ws->pivot.key1)\ && (temp.low.key2 == this_ws->pivot.key2)){ this_ws->flag_red_w_trivial = 1; this_ws->reduce_w_bndry = temp.triangle; this_ws->V_col_idx = 0; } else{ if (!self->g_H2_cohom_pivots_len[this_ws->pivot.key1]){ //printf("\npivot not in complex c1. append"); this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 1; continue; } else{ idx = search_H2_cohom_pivots(self->g_H2_cohom_pivots[this_ws->pivot.key1]\ , 0 \ , self->g_H2_cohom_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges); // If this low is not a pivot if (idx == self->g_n_valid_edges){ //printf("\npivot not in complex c2. append"); this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 1; continue; } else{ this_ws->flag_red_w_complex = 1; this_ws->reduce_w_bndry = self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].bndry; this_ws->V_col_idx = self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].col_idx; } } } } if ((!this_ws->flag_red_w_trivial) && (!this_ws->flag_red_w_complex)){ //printf("\nno red with trivial and no red with complex"); this_ws->flag_append_to_complex = 1; continue; } //printf("\nReducing..."); // Presume that this will be flagged to be added to complex this_ws->flag_red_w_complex = 0; this_ws->flag_red_w_trivial = 0; this_ws->flag_append_to_complex = 1; int flag = 0; while(1){ check_len = this_ws->v_triangles.last + 1; if (this_ws->V_col_idx){ check_len += self->g_V_col_indices[this_ws->V_col_idx+1] -\ self->g_V_col_indices[this_ws->V_col_idx]; } if (check_len > this_ws->v_triangles.max_len){ this_ws->v_triangles.max_len = check_len + 100; self->g_V_ws_H2[ws_counter].v_triangles.o_abc = \ (simplex*)realloc(self->g_V_ws_H2[ws_counter].v_triangles.o_abc\ , this_ws->v_triangles.max_len*sizeof(simplex)); } this_ws->v_triangles.o_abc[this_ws->v_triangles.last++] = this_ws->reduce_w_bndry; temp.triangle = this_ws->reduce_w_bndry; find_H2_cohom_greater(self, &(temp), &(this_ws->pivot)); //if (flag){ // printf("\ninserting (%d, %d):(%d, %d)"\ // , temp.triangle.key1\ // , temp.triangle.key2\ // , temp.low.key1\ // , temp.low.key2\ // ); //} //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nBefore inserting (%d, %d):(%d, %d)"\ // , temp.triangle.key1\ // , temp.triangle.key2\ // , temp.low.key1\ // , temp.low.key2\ // ); // coH2_print_v_implicit(self, ws_counter); //} coH2_insert_in_implicit_v(self, ws_counter, &(temp), 1); //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nAfter inserting"); // coH2_print_v_implicit(self, ws_counter); //} // IF the V was recorded, add the bndries if (this_ws->V_col_idx){ // We have to cycle through the col in V and add all the other boundary columns for reduction start = self->g_V_col_indices[this_ws->V_col_idx]; end = self->g_V_col_indices[this_ws->V_col_idx+1]; for (EDGE_ID mm = start; mm < end; mm++){ this_ws->v_triangles.o_abc[this_ws->v_triangles.last++] = self->g_V_sparse_H2[mm]; temp.triangle = self->g_V_sparse_H2[mm]; // Find the first low greater than or equal pivot find_H2_cohom_greater(self, &(temp), &(this_ws->pivot)); //if (flag){ // printf("\ninserting (%d, %d):(%d, %d)"\ // , temp.triangle.key1\ // , temp.triangle.key2\ // , temp.low.key1\ // , temp.low.key2\ // ); //} //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nBefore inserting (%d, %d):(%d, %d)"\ // , temp.triangle.key1\ // , temp.triangle.key2\ // , temp.low.key1\ // , temp.low.key2\ // ); // coH2_print_v_implicit(self, ws_counter); //} coH2_insert_in_implicit_v(self, ws_counter, &(temp), 1); //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nAfter inserting"); // coH2_print_v_implicit(self, ws_counter); //} } } //simplex test_low = this_ws->pivot; //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nBefore reduction"); // coH2_print_v_implicit(self, ws_counter); // printf("\nPivot is (%d, %d)"\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); // //} reduce_hash_table_coH2(self, ws_counter); //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nAfter reduction"); // coH2_print_v_implicit(self, ws_counter); // printf("\nPivot is (%d, %d)"\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); //} //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nNew pivot (%d, %d)", this_ws->pivot.key1\ // , this_ws->pivot.key2); // getchar(); //} //if ((test_low.key1 == this_ws->pivot.key1) // &&(test_low.key2 == this_ws->pivot.key2)){ // printf("\nprinting.."); // flag = 1; // coH2_print_v_implicit(self, ws_counter); // getchar(); //} //printf("\nNew low (%d, %d,)", this_ws->pivot.key1\ // , this_ws->pivot.key2); if (!this_ws->flag_non_empty){ break; } // Check with trivial pair temp.triangle.key1 = this_ws->pivot.key1; temp.triangle.key2 = self->g_edges_list[2*this_ws->pivot.key2+1]; find_H2_cohom_low(self, &temp); if ((temp.low.key1 == this_ws->pivot.key1)\ && (temp.low.key2 == this_ws->pivot.key2)){ //if (flag){ // printf("\nReducing with trivial (%d, %d)"\ // , temp.triangle.key1\ // , temp.triangle.key2\ // ); //} //printf("\nreduce with trivial"); this_ws->reduce_w_bndry = temp.triangle; this_ws->V_col_idx = 0; continue; } // If this low is not a pivot if (!self->g_H2_cohom_pivots_len[this_ws->pivot.key1]){ break; } idx = search_H2_cohom_pivots(self->g_H2_cohom_pivots[this_ws->pivot.key1]\ , 0 \ , self->g_H2_cohom_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges\ ); if (idx == self->g_n_valid_edges){ break; } //if (flag){ // for (EDGE_ID mm = 0; mm < self->g_H2_cohom_pivots_len[this_ws->pivot.key1]; mm++){ // printf("\n(%d, %d, %d), "\ // , self->g_H2_cohom_pivots[this_ws->pivot.key1][mm].key2\ // , self->g_H2_cohom_pivots[this_ws->pivot.key1][mm].bndry.key1\ // , self->g_H2_cohom_pivots[this_ws->pivot.key1][mm].bndry.key2\ // ); // } // printf("\nReducing with complex (%d, %d) at idx %d"\ // , self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].bndry.key1\ // , self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].bndry.key2\ // , idx\ // ); //} //printf("\nreduce with complex"); this_ws->reduce_w_bndry = self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].bndry; this_ws->V_col_idx = self->g_H2_cohom_pivots[this_ws->pivot.key1][idx].col_idx; } } } } void update_V_coH2(filtration* self, int ws_counter){ EDGE_ID red_col = 0; coboundary_H2_ws* this_ws = self->g_V_ws_H2 + ws_counter; //if ((this_ws->triangle.key1 == 227282)\ // &&(this_ws->triangle.key2 == 1807632)){ // // self->g_new_debug = 1; // //} //else{ // self->g_new_debug = 0; //} //if (self->g_new_debug){ // // printf("\n ADDDDDING %d, %d, %d, %d", this_ws->triangle.key1\ // , this_ws->triangle.key2\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); // getchar(); //} //printf("\nENTERING UPDATE_V_coH2"); self->g_V_sparse_beg_ptr = self->g_V_sparse_ptr; if (this_ws->v_triangles.last){ //printf("\n%d, %d, %d, %d", this_ws->triangle.key1\ // , this_ws->triangle.key2\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); if ((this_ws->v_triangles.last + self->g_V_sparse_ptr) + 1 > self->g_V_sparse_max){ self->g_V_sparse_max = self->g_V_sparse_ptr + this_ws->v_triangles.last + 100000; self->g_V_sparse_H2 = (simplex*)realloc(self->g_V_sparse_H2\ , self->g_V_sparse_max*sizeof(simplex)); } // //TRYING EDIT if (this_ws->v_triangles.last > 1){ #ifdef VREDUCE2 sorter4_tim_sort(this_ws->v_triangles.o_abc, this_ws->v_triangles.last); int coeff = 1; for (EDGE_ID vv = 0; vv < this_ws->v_triangles.last-1; vv++){ if ((this_ws->v_triangles.o_abc[vv].key1 == this_ws->v_triangles.o_abc[vv+1].key1) && (this_ws->v_triangles.o_abc[vv].key2 == this_ws->v_triangles.o_abc[vv+1].key2)) { coeff = 1 - coeff; } else{ if (coeff){ self->g_V_sparse_H2[self->g_V_sparse_ptr++] = this_ws->v_triangles.o_abc[vv]; } coeff = 1; } } if (coeff){ self->g_V_sparse_H2[self->g_V_sparse_ptr++] = this_ws->v_triangles.o_abc[this_ws->v_triangles.last-1]; } #else for (EDGE_ID vv = 0; vv < this_ws->v_triangles.last; vv++){ self->g_V_sparse_H2[self->g_V_sparse_ptr++] = this_ws->v_triangles.o_abc[vv]; } #endif } else if (this_ws->v_triangles.last == 1){ self->g_V_sparse_H2[self->g_V_sparse_ptr++] = this_ws->v_triangles.o_abc[0]; } // All have been added this_ws->v_triangles.last = 0; if ((self->g_V_sparse_ptr - self->g_V_sparse_beg_ptr) > 0){ red_col = self->g_V_col_indices_ptr; if (self->g_V_col_indices_ptr+1 == self->g_V_col_indices_max){ self->g_V_col_indices_max += 10000; self->g_V_col_indices = (EDGE_ID*)realloc(self->g_V_col_indices\ , self->g_V_col_indices_max*sizeof(EDGE_ID)); } self->g_V_col_indices[self->g_V_col_indices_ptr] = self->g_V_sparse_beg_ptr; self->g_V_col_indices[self->g_V_col_indices_ptr+1] = self->g_V_sparse_ptr; self->g_V_col_indices_ptr++; } } //printf("\n(%d, %d):(%d, %d)"\ // , this_ws->triangle.key1\ // , this_ws->triangle.key2\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); //printf("\nAdding v: "); // //for (EDGE_ID mm = self->g_V_sparse_beg_ptr; mm < self->g_V_sparse_ptr; mm++){ // printf("(%d, %d),", self->g_V_sparse_H2[mm].key1\ // , self->g_V_sparse_H2[mm].key2); //} //getchar(); // ADDING THE LOW // add_coH2_pivot(self, this_ws->triangle, this_ws->pivot, red_col); } void add_coH2_pivot (filtration* self, simplex triangle, simplex pivot, EDGE_ID red_col){ if (!self->g_H2_cohom_pivots_max_len[pivot.key1]){ self->g_H2_cohom_pivots_max_len[pivot.key1] = 2; self->g_H2_cohom_pivots[pivot.key1] = \ (H2_cohom_pivots*)malloc(self->g_H2_cohom_pivots_max_len[pivot.key1]*sizeof(H2_cohom_pivots)); } if (self->g_H2_cohom_pivots_len[pivot.key1]\ == self->g_H2_cohom_pivots_max_len[pivot.key1]){ self->g_H2_cohom_pivots_max_len[pivot.key1] += 5; self->g_H2_cohom_pivots[pivot.key1] = (H2_cohom_pivots*)realloc( \ self->g_H2_cohom_pivots[pivot.key1] \ , self->g_H2_cohom_pivots_max_len[pivot.key1]*sizeof(H2_cohom_pivots)); } EDGE_ID old_ptr = self->g_H2_cohom_pivots_len[pivot.key1]; EDGE_ID new_ptr = self->g_H2_cohom_pivots_len[pivot.key1]; while (old_ptr){ old_ptr--; if (self->g_H2_cohom_pivots[pivot.key1][old_ptr].key2 > pivot.key2){ self->g_H2_cohom_pivots[pivot.key1][new_ptr--] =\ self->g_H2_cohom_pivots[pivot.key1][old_ptr]; continue; } break; } self->g_H2_cohom_pivots[pivot.key1][new_ptr].key2 = pivot.key2; self->g_H2_cohom_pivots[pivot.key1][new_ptr].col_idx = red_col; self->g_H2_cohom_pivots[pivot.key1][new_ptr].bndry = triangle; self->g_H2_cohom_pivots_len[pivot.key1]++; // PERS PAIRS // Add non-zero barcodes PAR birth = self->g_edge_parameter[triangle.key1]; PAR death = self->g_edge_parameter[pivot.key1]; if (birth != death){ //printf("\nNon trivial pers pair (%f, %f)", birth, death); if (birth > death){ printf("\nBirth, death (%lf, %lf)", birth, death); printf("\nError (%d, %d) at pair (%d, %d)", triangle.key1\ , triangle.key2\ , pivot.key1\ , pivot.key2); getchar(); } if (self->g_H2_pers_pairs_len+2 == self->g_H2_pers_pairs_max_len){ self->g_H2_pers_pairs_max_len += 1000; self->g_H2_pers_pairs = (PAR*)realloc(self->g_H2_pers_pairs\ , self->g_H2_pers_pairs_max_len*sizeof(PAR)); } self->g_H2_pers_pairs[self->g_H2_pers_pairs_len++] = birth; self->g_H2_pers_pairs[self->g_H2_pers_pairs_len++] = death; } } void reduce_ws_coH2(filtration* self){ //printf("\nBefore parallel"); //for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ // printf("\n%d:(%d, %d) flag %d", self->g_V_ws_H1[mm].edge\ // , self->g_V_ws_H1[mm].pivot.key1\ // , self->g_V_ws_H1[mm].pivot.key2\ // , self->g_V_ws_H1[mm].flag_append_to_complex); // printf(" v: "); // for (EDGE_ID bb = 0; bb < self->g_V_ws_H1[mm].v_edges.last; bb++){ // printf("%d, ", self->g_V_ws_H1[mm].v_edges.o_ab[bb]); // } //} // // PARALLEL self->g_processed_threads = 0; pthread_cond_broadcast(&(self->g_start_workers)); while (self->g_processed_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ ,&(self->g_thread_lock)); } //printf("\nAfter parallel"); //for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ // printf("\n%d:(%d, %d) flag %d", self->g_V_ws_H1[mm].edge\ // , self->g_V_ws_H1[mm].pivot.key1\ // , self->g_V_ws_H1[mm].pivot.key2\ // , self->g_V_ws_H1[mm].flag_append_to_complex); // printf(" v: "); // for (EDGE_ID bb = 0; bb < self->g_V_ws_H1[mm].v_edges.last; bb++){ // printf("%d, ", self->g_V_ws_H1[mm].v_edges.o_ab[bb]); // } //} // SERIAL reduce_with_self_coH2(self); //printf("\nAfter serial"); //for (EDGE_ID mm = 0; mm < self->g_cohom_ws_size; mm++){ // printf("\n%d:(%d, %d) flag %d", self->g_V_ws_H1[mm].edge\ // , self->g_V_ws_H1[mm].pivot.key1\ // , self->g_V_ws_H1[mm].pivot.key2\ // , self->g_V_ws_H1[mm].flag_append_to_complex); // printf(" v: "); // for (EDGE_ID bb = 0; bb < self->g_V_ws_H1[mm].v_edges.last; bb++){ // printf("%d, ", self->g_V_ws_H1[mm].v_edges.o_ab[bb]); // } //} //getchar(); // CLEARANCE int count_valid = 0; for (int ws_counter = 0; ws_counter < self->g_ws_counter; ws_counter++){ if (!self->g_V_ws_H2[ws_counter].flag_non_empty){ // Add the undead H2 //printf("\nAdding undead for H2"); if (self->g_H2_pers_pairs_len+2 == self->g_H2_pers_pairs_max_len){ self->g_H2_pers_pairs_max_len += 1000; self->g_H2_pers_pairs = (PAR*)realloc(self->g_H2_pers_pairs\ , self->g_H2_pers_pairs_max_len*sizeof(PAR)); } self->g_H2_pers_pairs[self->g_H2_pers_pairs_len++] = \ self->g_edge_parameter[self->g_V_ws_H2[ws_counter].triangle.key1]; self->g_H2_pers_pairs[self->g_H2_pers_pairs_len++] = -1; //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H2_undead[self->g_H2_undead_ptr++] = self->g_V_ws_H2[ws_counter].triangle; if (self->g_H2_undead_ptr == self->g_H2_undead_max){ self->g_H2_undead_max += 100; self->g_H2_undead = (simplex*)realloc(self->g_H2_undead\ , self->g_H2_undead_max*sizeof(simplex)); } } //#endif //printf("\nEmpty. Not adding to complex."); continue; } if (self->g_V_ws_H2[ws_counter].flag_append_to_complex){ //printf("\nAdding to complex."); update_V_coH2(self, ws_counter); continue; } //printf("\nSwapping..."); // Swap V coboundary_H2_ws temp = self->g_V_ws_H2[count_valid]; self->g_V_ws_H2[count_valid] = self->g_V_ws_H2[ws_counter]; self->g_V_ws_H2[ws_counter] = temp; // At this point, this has to be a non-zero column self->g_V_ws_H2[count_valid].flag_non_empty = 1; // Run through parallel at least once self->g_V_ws_H2[count_valid].flag_append_to_complex = 0; count_valid++; } self->g_ws_counter = count_valid; } void reduce_hash_table_coH2(filtration* self, int ws_counter){ // Now we have to reduce int coeff = 1; coboundary_H2_ws* this_ws = self->g_V_ws_H2 + ws_counter; coboundary_H2 ttemp; EDGE_ID* k1_ptr = &(this_ws->k1_ptr); EDGE_ID* k2_ptr = &(this_ws->k2_ptr); while (1){ if (this_ws->keys1[*k1_ptr].last == 1){ this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2 ==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].k2){ coeff = 1 - coeff; if ((this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_abc.key1 ==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].o_abc.key1) && (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_abc.key2 ==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].o_abc.key2)) { if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next ==\ this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].flag_next){ this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next = 0; this_ws->keys1[*k1_ptr].keys2[*k2_ptr+1].flag_next = 0; } } } else{ if (coeff){ this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } else{ coeff = 1; } } if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next){ ttemp.triangle = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_abc; ttemp.a_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].a_ptr; ttemp.b_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].b_ptr; ttemp.c_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].c_ptr; ttemp.vertex = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].vertex; ttemp.low.key1 = this_ws->keys1[*k1_ptr].k1; ttemp.low.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; //if (this_ws->edge == self->g_debug_edge){ // printf("\nFinding next of %d:(%d, %d)", ttemp.o_ab\ // , ttemp.low.key1\ // , ttemp.low.key2\ // ); //} //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nFinding next of (%d, %d):(%d, %d)"\ // , ttemp.triangle.key1\ // , ttemp.triangle.key2\ // , ttemp.low.key1\ // , ttemp.low.key2\ // ); //} find_H2_cohom_next(self, &(ttemp)); //printf("\nInserting (%d, %d):(%d, %d)"\ // , ttemp.triangle.key1\ // , ttemp.triangle.key2\ // , ttemp.low.key1\ // , ttemp.low.key2\ // ); this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next = 0; coH2_insert_in_implicit_v(self, ws_counter, &(ttemp), 1); //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nAfter inserting"); // coH2_print_v_implicit(self, ws_counter); //} // It is possible that last key1 and last key2 changed. Make sure last is consistent } *k2_ptr = *k2_ptr + 1; if (*k2_ptr == this_ws->keys1[*k1_ptr].last-1){ if (coeff){ this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } if (this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next){ ttemp.triangle = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].o_abc; ttemp.a_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].a_ptr; ttemp.b_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].b_ptr; ttemp.c_ptr = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].c_ptr; ttemp.vertex = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].vertex; ttemp.low.key1 = this_ws->keys1[*k1_ptr].k1; ttemp.low.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; find_H2_cohom_next(self, &(ttemp)); this_ws->keys1[*k1_ptr].keys2[*k2_ptr].flag_next = 0; coH2_insert_in_implicit_v(self, ws_counter, &(ttemp), 1); } if (*k2_ptr == this_ws->keys1[*k1_ptr].last-2){ *k2_ptr = *k2_ptr + 1; this_ws->pivot.key1 = this_ws->keys1[*k1_ptr].k1; this_ws->pivot.key2 = this_ws->keys1[*k1_ptr].keys2[*k2_ptr].k2; break; } else{ // Mark this key1 as empty this_ws->keys1[*k1_ptr].flag_empty = 1; // Reallocate to prune space if (this_ws->keys1[*k1_ptr].max_len > 5){ this_ws->keys1[*k1_ptr].max_len = 5; self->g_V_ws_H2[ws_counter].keys1[*k1_ptr].keys2 = \ (coH2_implicit_keys2*)realloc\ (self->g_V_ws_H2[ws_counter].keys1[*k1_ptr].keys2\ , self->g_V_ws_H2[ws_counter].keys1[*k1_ptr].max_len\ *sizeof(coH2_implicit_keys2)); } EDGE_ID current_ptr = 0; EDGE_ID minn = self->g_n_valid_edges; for (EDGE_ID mm = 0; mm < this_ws->last; mm++){ if (this_ws->keys1[mm].flag_empty){ continue; } coH2_implicit_keys1 ttemp = this_ws->keys1[current_ptr]; this_ws->keys1[current_ptr] = this_ws->keys1[mm]; this_ws->keys1[mm] = ttemp; if (this_ws->keys1[current_ptr].k1 < minn){ minn = this_ws->keys1[current_ptr].k1; *k1_ptr = current_ptr; } current_ptr++; } this_ws->last = current_ptr; if (minn == self->g_n_valid_edges){ this_ws->flag_non_empty = 0; break; } // Otherwise reset coefficient and begin reduction coeff = 1; *k2_ptr = 0; sorter9_tim_sort(this_ws->keys1[*k1_ptr].keys2\ , this_ws->keys1[*k1_ptr].last); } } } } void coH2_insert_in_implicit_v(filtration* self, int ws_counter, coboundary_H2* phi, int flag_next){ if (phi->low.key1 == self->g_n_valid_edges){ return; } coboundary_H2_ws* this_ws = self->g_V_ws_H2 + ws_counter; //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nINSERTING (%d, %d):(%d, %d)"\ // , phi->triangle.key1\ // , phi->triangle.key2\ // , phi->low.key1\ // , phi->low.key2\ // ); //} if (phi->low.key1 == this_ws->keys1[this_ws->k1_ptr].k1){ if (this_ws->keys1[this_ws->k1_ptr].last ==\ this_ws->keys1[this_ws->k1_ptr].max_len){ self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].max_len += 10; self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].keys2 = \ (coH2_implicit_keys2*)realloc\ (self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].keys2\ , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].max_len\ *sizeof(coH2_implicit_keys2)); } EDGE_ID mm = this_ws->keys1[this_ws->k1_ptr].last; coH2_implicit_keys2* this_key2 = &(this_ws->keys1[this_ws->k1_ptr].keys2[mm-1]); int compare; while (1){ //int compare = coH2_compare_implicit(this_ws->keys1[this_ws->k1_ptr].keys2[mm-1], *phi); //if (this_ws->keys1[this_ws->k1_ptr].keys2[mm-1].k2 < phi->low.key2) compare = 0; //else if (this_ws->keys1[this_ws->k1_ptr].keys2[mm-1].k2 > phi->low.key2) compare = 1; if (this_key2->k2 < phi->low.key2) compare = 0; else if (this_key2->k2 > phi->low.key2) compare = 1; else{ if (this_key2->o_abc.key1 < phi->triangle.key1) compare = 0; else if (this_key2->o_abc.key1 > phi->triangle.key1) compare = 1; else{ if (this_key2->o_abc.key2 < phi->triangle.key2) compare = 0; else compare = 1; } } if (compare){ this_ws->keys1[this_ws->k1_ptr].keys2[mm] =\ this_ws->keys1[this_ws->k1_ptr].keys2[mm-1]; } else{ //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c1"); // coH2_print_v_implicit(self, ws_counter); //} coH2_implicit_keys1* this_key1 = &(this_ws->keys1[this_ws->k1_ptr]); coH2_implicit_keys2* this_key2 = &(this_key1->keys2[mm]); this_key2->k2 = phi->low.key2; this_key2->o_abc = phi->triangle; this_key2->a_ptr = phi->a_ptr; this_key2->b_ptr = phi->b_ptr; this_key2->c_ptr = phi->c_ptr; this_key2->vertex = phi->vertex; this_key2->flag_next = flag_next; this_ws->keys1[this_ws->k1_ptr].last++; //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c2"); // coH2_print_v_implicit(self, ws_counter); //} return; } this_key2--; mm--; //// ERROR CHECKING, REMOVE LATER //if (!mm){ // printf("\nk2_ptr %d", v_implicit->k2_ptr); // printf("\nADDING %d:(%d, %d) to ", phi->o_ab, phi->low.key1, phi->low.key2); // print_v_implicit(self); // exit(0); // //} if (mm == this_ws->k2_ptr){ //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c3, idx %d, last is %d"\ // , self->g_V_ws_H2[ws_counter].k1_ptr\ // , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].last); // coH2_print_v_implicit(self, ws_counter); //} coH2_implicit_keys1* this_key1 = &(this_ws->keys1[this_ws->k1_ptr]); coH2_implicit_keys2* this_key2 = &(this_key1->keys2[mm]); this_key2->k2 = phi->low.key2; this_key2->o_abc = phi->triangle; this_key2->a_ptr = phi->a_ptr; this_key2->b_ptr = phi->b_ptr; this_key2->c_ptr = phi->c_ptr; this_key2->vertex = phi->vertex; this_key2->flag_next = flag_next; this_ws->keys1[this_ws->k1_ptr].last++; //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c4, idx %d, last is %d"\ // , self->g_V_ws_H2[ws_counter].k1_ptr\ // , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].last); // coH2_print_v_implicit(self, ws_counter); //} return; } } } for (EDGE_ID mm = 0; mm < self->g_V_ws_H2[ws_counter].last; mm++){ if (self->g_V_ws_H2[ws_counter].keys1[mm].k1 == phi->low.key1){ //check_space_implicit_keys2(&(v_implicit->keys1[mm])); if (self->g_V_ws_H2[ws_counter].keys1[mm].last ==\ self->g_V_ws_H2[ws_counter].keys1[mm].max_len){ self->g_V_ws_H2[ws_counter].keys1[mm].max_len += 10; self->g_V_ws_H2[ws_counter].keys1[mm].keys2 = (coH2_implicit_keys2*)realloc\ (self->g_V_ws_H2[ws_counter].keys1[mm].keys2\ , self->g_V_ws_H2[ws_counter].keys1[mm].max_len*sizeof(coH2_implicit_keys2)); } //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c5, idx %d, last is %d"\ // , self->g_V_ws_H2[ws_counter].k1_ptr\ // , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].last); // coH2_print_v_implicit(self, ws_counter); //} coH2_implicit_keys1* this_key1 = &(this_ws->keys1[mm]); coH2_implicit_keys2* this_key2 = &(this_key1->keys2[this_key1->last]); this_ws->keys1[mm].flag_empty = 0; this_key2->k2 = phi->low.key2; this_key2->o_abc = phi->triangle; this_key2->a_ptr = phi->a_ptr; this_key2->b_ptr = phi->b_ptr; this_key2->c_ptr = phi->c_ptr; this_key2->vertex = phi->vertex; this_key2->flag_next = flag_next; this_key1->last++; //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c6, idx %d, last is %d"\ // , self->g_V_ws_H2[ws_counter].k1_ptr\ // , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].last); // coH2_print_v_implicit(self, ws_counter); //} return; } } if (self->g_V_ws_H2[ws_counter].last == self->g_V_ws_H2[ws_counter].max_len){ EDGE_ID mm = self->g_V_ws_H2[ws_counter].max_len; self->g_V_ws_H2[ws_counter].max_len += 10; self->g_V_ws_H2[ws_counter].keys1 = (coH2_implicit_keys1*)realloc(self->g_V_ws_H2[ws_counter].keys1\ , self->g_V_ws_H2[ws_counter].max_len*sizeof(coH2_implicit_keys1)); while (mm < self->g_V_ws_H2[ws_counter].max_len){ this_ws->keys1[mm].flag_empty = 1; this_ws->keys1[mm].max_len = 10; this_ws->keys1[mm].last = 0; self->g_V_ws_H2[ws_counter].keys1[mm].keys2 = (coH2_implicit_keys2*)malloc(10*sizeof(coH2_implicit_keys2)); mm++; } } //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c7, idx %d, last is %d"\ // , self->g_V_ws_H2[ws_counter].k1_ptr\ // , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].last); // coH2_print_v_implicit(self, ws_counter); //} coH2_implicit_keys1* this_key1 = &(this_ws->keys1[this_ws->last]); coH2_implicit_keys2* this_key2 = &(this_key1->keys2[0]); this_key1->flag_empty = 0; this_key1->k1 = phi->low.key1; this_key2->k2 = phi->low.key2; this_key2->o_abc = phi->triangle; this_key2->a_ptr = phi->a_ptr; this_key2->b_ptr = phi->b_ptr; this_key2->c_ptr = phi->c_ptr; this_key2->vertex = phi->vertex; this_key2->flag_next = flag_next; this_key1->last = 1; this_ws->last++; //if ((this_ws->triangle.key1 == self->g_debug_triangle.key1) &&\ // (this_ws->triangle.key2 == self->g_debug_triangle.key2)){ // printf("\nin c7, idx %d, last is %d"\ // , self->g_V_ws_H2[ws_counter].k1_ptr\ // , self->g_V_ws_H2[ws_counter].keys1[self->g_V_ws_H2[ws_counter].k1_ptr].last); // coH2_print_v_implicit(self, ws_counter); //} return; } BIGINT compute_num_simplices(filtration* self){ self->g_n_all_simp = (BIGINT)(self->g_n_vert) + (BIGINT)(self->g_n_valid_edges); printf("\n"); for (EDGE_ID o_ab = 0; o_ab < self->g_n_valid_edges; o_ab++){ printf("\redge%d", o_ab); VERT_ID a = self->g_edges_list[2*o_ab]; VERT_ID b = self->g_edges_list[2*o_ab+1]; VERT_ID a_ptr = 0; VERT_ID b_ptr = 0; while ((a_ptr < self->g_Neigh_len[a])\ && (b_ptr < self->g_Neigh_len[b])){ if (self->g_Neighbors[a][a_ptr].neighbor < self->g_Neighbors[b][b_ptr].neighbor){ a_ptr++; } else if (self->g_Neighbors[a][a_ptr].neighbor > self->g_Neighbors[b][b_ptr].neighbor){ b_ptr++; } else{ VERT_ID c = self->g_Neighbors[a][a_ptr].neighbor; EDGE_ID o_ac = self->g_Neighbors[a][a_ptr].order; if (o_ac > o_ab){ a_ptr++; b_ptr++; continue; } EDGE_ID o_bc = self->g_Neighbors[b][b_ptr].order; if (o_bc > o_ab){ a_ptr++; b_ptr++; continue; } // This is a valid triangle self->g_n_all_simp++; for (VERT_ID mm = 0; mm < self->g_Neigh_len[c]; mm++){ if (self->g_Neighbors[c][mm].neighbor < c){ continue; } VERT_ID d = self->g_Neighbors[c][mm].neighbor; VERT_ID idx = search_Neighbors(self, a, d, 0, self->g_Neigh_len[a]-1); if (idx == self->g_n_vert) continue; EDGE_ID o_ad = self->g_Neighbors[a][idx].order; if (o_ad > o_ab) continue; idx = search_Neighbors(self, b, d, 0, self->g_Neigh_len[b]-1); if (idx == self->g_n_vert) continue; EDGE_ID o_bd = self->g_Neighbors[b][idx].order; if (o_bd > o_ab) continue; idx = search_Neighbors(self, c, d, 0, self->g_Neigh_len[c]-1); if (idx == self->g_n_vert) continue; EDGE_ID o_cd = self->g_Neighbors[c][idx].order; if (o_cd > o_ab) continue; self->g_n_all_simp++; //printf("\n %d, %d, %d, %d", a, b, c, d); } a_ptr++; b_ptr++; } } } printf("\nNumber of simplices %llu\n", self->g_n_all_simp); } void compute_H1_homology_cycles(filtration* self){ /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // // STEP H1.1: Find homology now for the triangles // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// if (!self->g_suppress_output){ printf("\n\n---------------"); printf("\nComputing H1..."); printf("\n---------------\n"); } struct timespec start_wall_clock, finish_wall_clock; clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); self->g_R_max_len_H1 = 100; self->g_R_H1 = (EDGE_ID*)malloc(self->g_R_max_len_H1*sizeof(EDGE_ID)); self->g_R_len_H1 = 0; self->g_R_col_idx_max_len_H1 = 100; self->g_R_col_idx_H1 = (EDGE_ID*)malloc(self->g_R_col_idx_max_len_H1*sizeof(EDGE_ID)); self->g_R_col_idx_H1_ptr = 0; self->g_workspace_size = 1000; self->g_ws_pre_alloc = 1000; // Initialize ws counter self->g_ws_counter = 0; // H1 workspace structures self->g_workspace_H1 = (EDGE_ID**)malloc(self->g_workspace_size*sizeof(EDGE_ID*)); // H1 workspace info self->g_workspace_H1_info = (boundary_H1_ws*)malloc(self->g_workspace_size*sizeof(boundary_H1_ws)); for (int i = 0; i < self->g_workspace_size; i++){ self->g_workspace_H1_info[i].max_len = self->g_ws_pre_alloc; self->g_workspace_H1[i] = (EDGE_ID*)malloc(2*self->g_workspace_H1_info[i].max_len*sizeof(EDGE_ID)); self->g_workspace_H1_info[i].trivial_boundary = (EDGE_ID*)malloc(3*sizeof(EDGE_ID)); } // Pivots self->g_pivots_H1 = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); // Convenient info for pers pairs self->g_homH1_pers_len = 0; self->g_homH1_pers_max_len = 100; self->g_homH1_pers = (homH1_pers*)malloc(self->g_homH1_pers_max_len*sizeof(homH1_pers)); // Temporary space for birth cycles self->g_temp_V_primary.max_len = 10; self->g_temp_V_primary.VV = (EDGE_ID*)malloc(self->g_temp_V_primary.max_len*sizeof(EDGE_ID)); self->g_temp_V_primary.len = 0; // Temporary space for birth cycles self->g_temp_R_birth_cycles.max_len = 100; self->g_temp_R_birth_cycles.RR = (EDGE_ID*)malloc(2*self->g_temp_R_birth_cycles.max_len*sizeof(EDGE_ID)); self->g_temp_R_birth_cycles.original = 0; self->g_temp_R_birth_cycles.len = 0; //#ifdef HOM_CYCLES // Need this info for birth voids if (self->g_compute_cycles){ self->g_H1_pivot_of = (V_H1*)malloc(self->g_n_valid_edges*sizeof(V_H1)); } //#endif #ifdef ADAPTIVE_V_STORAGE // Create pointers to store V if (self->g_compute_cycles){ for (EDGE_ID mm = 0; mm < self->g_n_vert; mm++){ self->g_H0_pivot_of[mm].V_usage = 0; self->g_H0_pivot_of[mm].V_stored = 0; self->g_H0_pivot_of[mm].V_len = 0; self->g_H0_pivot_of[mm].VV = NULL; } } // Create pointers to store V per extraction call self->g_store_V_for_len = 0; self->g_store_V_for_max_len = 10; self->g_store_V_for = (EDGE_ID*)malloc(self->g_store_V_for_max_len*sizeof(EDGE_ID)); #endif //#ifdef MINIMIZE_BIRTH_CYCLES //if (self->g_reduce_cyc_lengths){ self->g_all_V_stored_num = 0; self->g_all_V_stored_max_num = 10; //self->g_all_V_stored_len = (EDGE_ID*)calloc(self->g_all_V_stored_max_num, sizeof(EDGE_ID)); //self->g_all_V_H0_stored = (EDGE_ID**)malloc(self->g_all_V_stored_max_num*sizeof(EDGE_ID*)); self->g_all_V_H0_stored = (cyc_info*)malloc(self->g_all_V_stored_max_num*sizeof(cyc_info)); self->g_edges_in_cycles = (EDGE_ID**)malloc(self->g_n_valid_edges*sizeof(EDGE_ID*)); self->g_edges_in_cycles_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); //} //#endif #ifdef MINIMIZE_HOM_CYCLES self->g_all_R_hom_stored_num = 0; self->g_all_R_hom_stored_max_num = 10; //self->g_all_R_hom_stored_len = (EDGE_ID*)calloc(self->g_all_V_hom_stored_max_num, sizeof(EDGE_ID)); //self->g_all_V_hom_H1_stored = (EDGE_ID**)malloc(self->g_all_V_hom_stored_max_num*sizeof(EDGE_ID*)); self->g_all_R_hom_H1_stored = (cyc_info*)malloc(self->g_all_R_hom_stored_max_num*sizeof(cyc_info)); #endif //////////////////////////////////////////////////////////////// // // Allocate jobs for parallel H1 // //////////////////////////////////////////////////////////////// self->g_jobs = (int*)malloc((self->g_cpu_count + 1)*sizeof(int)); allocate_jobs(self, self->g_workspace_size); self->g_threads = (pthread_t *)malloc(self->g_cpu_count*sizeof(pthread_t)); int rtn; if ((rtn = pthread_mutex_init(&(self->g_thread_lock), NULL)) !=0) fprintf(stderr, "pthread_mutex_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_boss), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_workers), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); // Initialize thread creation self->g_thread_id = 0; self->g_sleeping_threads = 0; self->g_delete_threads = 0; for (int i = 0; i < self->g_cpu_count; i++){ if ((rtn = pthread_create( \ &(self->g_threads[i]) \ , NULL \ , reduce_with_complex_H1 \ , (void*)self)!= 0)) fprintf(stderr, "pthread_create %d", rtn), exit(-1); } // Wait for threads to be initialized pthread_mutex_lock(&(self->g_thread_lock)); while(self->g_sleeping_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ , &(self->g_thread_lock)); } //////////////////////////////// // STEP 1: Compute R (Note: Do not include trivial pairs) for (EDGE_ID o_ab = 0; o_ab < self->g_n_valid_edges; o_ab++){ if (!self->g_H1_cohom_pivots_len[o_ab]){ continue; } VERT_ID a = self->g_edges_list[2*o_ab]; VERT_ID b = self->g_edges_list[2*o_ab+1]; for (VERT_ID mm = 0; mm < self->g_H1_cohom_pivots_len[o_ab]; mm++){ //This triangle is in a non-trivial persistence pair // Workspace attributes boundary_H1_ws* this_ws = self->g_workspace_H1_info + self->g_ws_counter; // Initially, the original is at 0 this_ws->original = 0; this_ws->flag_first = 1; // Parallel control flags this_ws->flag_empty = 0; this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 1; this_ws->triangle.key1 = o_ab; this_ws->triangle.key2 = self->g_H1_cohom_pivots[o_ab][mm].key2; // Initial length of boundary this_ws->len = 3; compute_boundary_triangle(self, this_ws->triangle, self->g_workspace_H1[self->g_ws_counter]); this_ws->pivot = o_ab; //printf("\nOutside the boundary is (%d, %d, %d)"\ // , self->g_workspace_H1[self->g_ws_counter][0]\ // , self->g_workspace_H1[self->g_ws_counter][1]\ // , self->g_workspace_H1[self->g_ws_counter][2]\ // ); self->g_ws_counter++; if (self->g_ws_counter == self->g_workspace_size){ reduce_ws_H1(self); } } } //printf("\n press key for the last batch"); //self->g_new_debug2 = 1; //getchar(); // Reduction of final batch while (self->g_ws_counter){ allocate_jobs(self, self->g_ws_counter); reduce_ws_H1(self); } //printf("\nComputed H1."); //getchar(); ///////////////////////// // Cancel the threads ///////////////////////// self->g_delete_threads = 1; pthread_cond_broadcast(&(self->g_start_workers)); pthread_mutex_unlock(&(self->g_thread_lock)); for (int i = 0; i < self->g_cpu_count; i++){ pthread_join(self->g_threads[i], NULL); } free(self->g_jobs); free(self->g_threads); // CANNOT FREE THIS IS H2 CYCLES ARE NEEDED //free(self->g_R_H1); //free(self->g_R_col_idx_H1); //free(self->g_pivots_H1); for (int i = 0; i < self->g_workspace_size; i++){ free(self->g_workspace_H1_info[i].trivial_boundary); free(self->g_workspace_H1[i]); } free(self->g_workspace_H1); free(self->g_workspace_H1_info); if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_computeH1 = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_computeH1 += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; printf("\nComputed H1."); //////////////////////// // HOMOLOGY CYCLES //////////////////////// clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); } FILE* fp2 = fopen(self->g_homH1_cycles_file, "w"); PAR birth, death; self->g_n_H1_birth_cycles = 0; self->g_n_H0_stored_V = 0; int add_flag = 0; // Go over the pers pairs of features that died and compute the cycles for (EDGE_ID mm = 0; mm < self->g_homH1_pers_len; mm++){ //if (n_cycles%1000 == 0) printf("\r Computing cycle num %llu", n_cycles); self->g_n_H1_birth_cycles++; if (self->g_filetype == 1){ birth = sqrt(self->g_edge_parameter[self->g_homH1_pers[mm].birth_edge]); death = sqrt(self->g_edge_parameter[self->g_homH1_pers[mm].death_triangle_key1]); } else{ birth = self->g_edge_parameter[self->g_homH1_pers[mm].birth_edge]; death = self->g_edge_parameter[self->g_homH1_pers[mm].death_triangle_key1]; } fprintf(fp2, "%lf, %lf", birth , death); fprintf(fp2, "\nhomology cycle"); #ifdef MINIMIZE_HOM_CYCLES self->g_all_V_hom_stored_len[self->g_all_V_hom_stored_num] =\ self->g_R_col_idx_H1[self->g_homH1_pers[mm].R_col_idx + 1]\ - self->g_R_col_idx_H1[self->g_homH1_pers[mm].R_col_idx]; self->g_all_V_hom_H1_stored[self->g_all_V_hom_stored_num] =\ (EDGE_ID*)\ malloc(self->g_all_V_hom_stored_len[self->g_all_V_hom_stored_num]\ *sizeof(EDGE_ID)); EDGE_ID bbb = 0; #endif for (EDGE_ID bb = self->g_R_col_idx_H1[self->g_homH1_pers[mm].R_col_idx]\ ; bb < self->g_R_col_idx_H1[self->g_homH1_pers[mm].R_col_idx + 1]\ ; bb++){ fprintf(fp2, ", %d, %d", self->g_edges_list[2*self->g_R_H1[bb]]\ , self->g_edges_list[2*self->g_R_H1[bb]+1]); #ifdef MINIMIZE_HOM_CYCLES self->g_all_V_hom_H1_stored[self->g_all_V_hom_stored_num][bbb++] = self->g_R_H1[bb]; #endif } #ifdef MINIMIZE_HOM_CYCLES self->g_all_V_hom_stored_num++; if (self->g_all_V_hom_stored_num == self->g_all_V_hom_stored_max_num){ self->g_all_V_hom_stored_max_num += 100; self->g_all_V_hom_H1_stored = (EDGE_ID**)realloc(self->g_all_V_hom_H1_stored\ , self->g_all_V_hom_stored_max_num*sizeof(EDGE_ID*)); self->g_all_V_hom_stored_len = (EDGE_ID*)realloc(self->g_all_V_hom_stored_len\ , self->g_all_V_hom_stored_max_num*sizeof(EDGE_ID)); } #endif // Always store the birth cycles for now fprintf(fp2, "\nbirth cycle"); //printf("\nGetting birth cycle %d out of %d", mm, self->g_homH1_pers_len); //getchar(); #ifdef ADAPTIVE_V_STORAGE self->g_store_V_for_len = 0; #endif get_birth_cycle(self, self->g_homH1_pers[mm].birth_edge); //#ifdef MINIMIZE_BIRTH_CYCLES //if (self->g_reduce_cyc_lengths){ ///self->g_all_V_stored_len[self->g_all_V_stored_num] = self->g_temp_V_primary.len; ///self->g_all_V_H0_stored[self->g_all_V_stored_num] =\ /// (EDGE_ID*)malloc(self->g_temp_V_primary.len*sizeof(EDGE_ID)); //add_flag = 1; //if (death - birth > 4){ // add_flag = 1; //} //if (add_flag){ self->g_all_V_H0_stored[self->g_all_V_stored_num].boundary =\ (EDGE_ID*)malloc(self->g_temp_V_primary.len*sizeof(EDGE_ID)); self->g_all_V_H0_stored[self->g_all_V_stored_num].len = self->g_temp_V_primary.len; //self->g_all_V_H0_stored[self->g_all_V_stored_num].ops_len = 1; //self->g_all_V_H0_stored[self->g_all_V_stored_num].ops = (EDGE_ID*)malloc(sizeof(EDGE_ID)); //self->g_all_V_H0_stored[self->g_all_V_stored_num].ops[0] = self->g_all_V_stored_num; self->g_all_V_H0_stored[self->g_all_V_stored_num].perspair[0] = birth; self->g_all_V_H0_stored[self->g_all_V_stored_num].perspair[1] = death; self->g_all_V_H0_stored[self->g_all_V_stored_num].updated_birth = birth; //printf("\n%d idx is pers pair (%lf, %lf) has len %d"\ // , self->g_all_V_stored_num\ // , birth\ // , death\ // , self->g_temp_V_primary.len); //} //} //#endif for (EDGE_ID nn = 0; nn < self->g_temp_V_primary.len; nn++){ fprintf(fp2, ", %d, %d", self->g_edges_list[2*self->g_temp_V_primary.VV[nn]]\ , self->g_edges_list[2*self->g_temp_V_primary.VV[nn]+1]); //#ifdef MINIMIZE_BIRTH_CYCLES //if (self->g_reduce_cyc_lengths){ self->g_all_V_H0_stored[self->g_all_V_stored_num].boundary[nn] = self->g_temp_V_primary.VV[nn]; //} //#endif } fprintf(fp2, "\n"); //#ifdef MINIMIZE_BIRTH_CYCLES //if (add_flag){ //if (self->g_reduce_cyc_lengths){ self->g_all_V_stored_num++; if (self->g_all_V_stored_num == self->g_all_V_stored_max_num){ self->g_all_V_stored_max_num += 100; self->g_all_V_H0_stored = (cyc_info*)realloc(self->g_all_V_H0_stored\ , self->g_all_V_stored_max_num*sizeof(cyc_info)); //self->g_all_V_stored_len = (EDGE_ID*)realloc(self->g_all_V_stored_len\ // , self->g_all_V_stored_max_num*sizeof(EDGE_ID)); } //} //#endif #ifdef ADAPTIVE_V_STORAGE store_V_H0(self); #endif } // Go over the pers pairs of undead features and compute the birth cycles for (EDGE_ID mm = 0; mm < self->g_H1_undead_ptr; mm++){ self->g_n_H1_birth_cycles++; if (self->g_filetype == 1){ birth = sqrt(self->g_edge_parameter[self->g_H1_undead[mm]]); } else{ birth = self->g_edge_parameter[self->g_H1_undead[mm]]; } fprintf(fp2, "%lf, -1", birth); #ifdef ADAPTIVE_V_STORAGE self->g_store_V_for_len = 0; #endif get_birth_cycle(self, self->g_H1_undead[mm]); //#ifdef MINIMIZE_BIRTH_CYCLES //if (self->g_reduce_cyc_lengths){ //self->g_all_V_stored_len[self->g_all_V_stored_num] = self->g_temp_V_primary.len; //self->g_all_V_H0_stored[self->g_all_V_stored_num] =\ // (EDGE_ID*)malloc(self->g_temp_V_primary.len*sizeof(EDGE_ID)); self->g_all_V_H0_stored[self->g_all_V_stored_num].boundary =\ (EDGE_ID*)malloc(self->g_temp_V_primary.len*sizeof(EDGE_ID)); self->g_all_V_H0_stored[self->g_all_V_stored_num].len = self->g_temp_V_primary.len; //self->g_all_V_H0_stored[self->g_all_V_stored_num].ops_len = 1; //self->g_all_V_H0_stored[self->g_all_V_stored_num].ops = (EDGE_ID*)malloc(sizeof(EDGE_ID)); //self->g_all_V_H0_stored[self->g_all_V_stored_num].ops[0] = self->g_all_V_stored_num; self->g_all_V_H0_stored[self->g_all_V_stored_num].perspair[0] = birth; self->g_all_V_H0_stored[self->g_all_V_stored_num].perspair[1] = -1; self->g_all_V_H0_stored[self->g_all_V_stored_num].updated_birth = birth; //} //#endif fprintf(fp2, "\nbirth cycle"); for (EDGE_ID nn = 0; nn < self->g_temp_V_primary.len; nn++){ fprintf(fp2, ", %d, %d", self->g_edges_list[2*self->g_temp_V_primary.VV[nn]]\ , self->g_edges_list[2*self->g_temp_V_primary.VV[nn]+1]); //#ifdef MINIMIZE_BIRTH_CYCLES //if (self->g_reduce_cyc_lengths){ self->g_all_V_H0_stored[self->g_all_V_stored_num].boundary[nn] = self->g_temp_V_primary.VV[nn]; //} //#endif } fprintf(fp2, "\n"); //#ifdef MINIMIZE_BIRTH_CYCLES //if (self->g_reduce_cyc_lengths){ self->g_all_V_stored_num++; if (self->g_all_V_stored_num == self->g_all_V_stored_max_num){ self->g_all_V_stored_max_num += 100; self->g_all_V_H0_stored = (cyc_info*)realloc(self->g_all_V_H0_stored\ , self->g_all_V_stored_max_num*sizeof(cyc_info)); //self->g_all_V_stored_len = (EDGE_ID*)realloc(self->g_all_V_stored_len\ // , self->g_all_V_stored_max_num*sizeof(EDGE_ID)); } //} //#endif #ifdef ADAPTIVE_V_STORAGE store_V_H0(self); #endif } fclose(fp2); free(self->g_homH1_pers); free(self->g_temp_V_primary.VV); free(self->g_temp_R_birth_cycles.RR); #ifdef RECORD_V_USAGE FILE* fp3 = fopen(self->g_V_H0_usage_file, "w"); #endif for (EDGE_ID mm = 0; mm < self->g_n_vert; mm++){ if (self->g_H0_pivot_of[mm].V_len){ #ifdef RECORD_V_USAGE fprintf(fp3, "%d, %d\n"\ , self->g_H0_pivot_of[mm].V_usage\ , self->g_H0_pivot_of[mm].V_depth); #endif //printf("\n%d is used %d times with depth %d"\ // , mm\ // , self->g_H0_pivot_of[mm].V_usage\ // , self->g_H0_pivot_of[mm].V_depth\ // ); free(self->g_H0_pivot_of[mm].VV); } } #ifdef RECORD_V_USAGE fclose(fp3); #endif free(self->g_H0_pivot_of); //printf("\nPress key to continue..."); //getchar(); #ifdef ADAPTIVE_V_STORAGE free(self->g_store_V_for); #endif if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_H1cycles = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_H1cycles += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; } //if (self->g_reduce_cyc_lengths){ struct timespec start_wall_clock2, finish_wall_clock2; if (!self->g_suppress_output){ printf("\nMinimizing birth cycles..."); clock_gettime(CLOCK_MONOTONIC, &start_wall_clock2); } minimize_birth_cycles_H0_v3(self\ , self->g_all_V_H0_stored\ , self->g_all_V_stored_num\ , self->g_minimal_V_H0_file\ , self->g_V_H0_birthcyc_lens_file\ , self->g_minimal_V_H0_birthcyc_lens_file\ , self->g_birth_subset_points_file_H0\ ); //, self->g_minimal_V_H0_in_cycles_file\ if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock2); self->g_timer_minimize_H1cycles = (finish_wall_clock2.tv_sec - start_wall_clock2.tv_sec); self->g_timer_minimize_H1cycles += (finish_wall_clock2.tv_nsec - start_wall_clock2.tv_nsec) / 1000000000.0; } //} //else{ // for (EDGE_ID ci = 0; ci < self->g_all_V_stored_num; ci++){ // free(self->g_all_V_H0_stored[ci].boundary); // } //} #ifdef MINIMIZE_HOM_CYCLES if (!self->g_suppress_output){ printf("\nMinimizing hom cycles..."); clock_gettime(CLOCK_MONOTONIC, &start_wall_clock2); } minimize_birth_cycles_H0_v3(self, self->g_all_V_hom_H1_stored\ , self->g_all_V_hom_stored_len\ , self->g_all_V_hom_stored_num\ , self->g_minimal_V_hom_H1_file\ , self->g_birth_subset_points_file_H0\ ); if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock2); self->g_timer_minimize_H1_homcycles = (finish_wall_clock2.tv_sec - start_wall_clock2.tv_sec); self->g_timer_minimize_H1_homcycles += (finish_wall_clock2.tv_nsec - start_wall_clock2.tv_nsec) / 1000000000.0; } #endif if (!self->g_suppress_output){ printf("\nComputed homology and birth cycles for H1."); } //getchar(); } void reduce_ws_H1(filtration* self){ if (self->g_new_debug2){ for (int kk = 0; kk < self->g_ws_counter; kk++){ printf("\n%d has triangle (%d, %d) with pivot %d", kk\ , self->g_workspace_H1_info[kk].triangle.key1\ , self->g_workspace_H1_info[kk].triangle.key2\ , self->g_workspace_H1_info[kk].pivot\ ); } printf("\nbefore parallel. press key to start parallel"); //getchar(); } self->g_processed_threads = 0; //printf("\npress key to reduce with complex"); //getchar(); pthread_cond_broadcast(&(self->g_start_workers)); while (self->g_processed_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ ,&(self->g_thread_lock)); } //printf("\npress key to reduce with self"); //getchar(); if (self->g_new_debug2){ for (int kk = 0; kk < self->g_ws_counter; kk++){ printf("\n%d has triangle (%d, %d) with pivot %d", kk\ , self->g_workspace_H1_info[kk].triangle.key1\ , self->g_workspace_H1_info[kk].triangle.key2\ , self->g_workspace_H1_info[kk].pivot\ ); } printf("\nafter parallel. press key to start serial"); //getchar(); } reduce_with_self_H1( \ self \ ); if (self->g_new_debug2){ for (int kk = 0; kk < self->g_ws_counter; kk++){ printf("\n%d has triangle (%d, %d) with pivot %d", kk\ , self->g_workspace_H1_info[kk].triangle.key1\ , self->g_workspace_H1_info[kk].triangle.key2\ , self->g_workspace_H1_info[kk].pivot\ ); } printf("\nafter serial. press key to update "); //getchar(); } int count_valid = 0; for (int ws_counter=0; ws_counter < self->g_ws_counter; ws_counter++){ if (self->g_workspace_H1_info[ws_counter].flag_append_to_complex){ update_R_H1(self \ , ws_counter\ ); continue; } //if (!self->g_workspace_H1_info[ws_counter].len){continue;} if (self->g_workspace_H1_info[ws_counter].flag_empty){ continue; } // Swap R EDGE_ID* temp = self->g_workspace_H1[count_valid]; self->g_workspace_H1[count_valid] = self->g_workspace_H1[ws_counter]; self->g_workspace_H1[ws_counter] = temp; // Swap R info boundary_H1_ws temp2 = self->g_workspace_H1_info[count_valid]; self->g_workspace_H1_info[count_valid] = self->g_workspace_H1_info[ws_counter]; self->g_workspace_H1_info[ws_counter] = temp2; // At this point, this has to be a non-zero column self->g_workspace_H1_info[count_valid].flag_empty = 0; count_valid += 1; } self->g_ws_counter = count_valid; if (self->g_new_debug2){ for (int kk = 0; kk < self->g_ws_counter; kk++){ printf("\n%d has triangle (%d, %d) with pivot %d", kk\ , self->g_workspace_H1_info[kk].triangle.key1\ , self->g_workspace_H1_info[kk].triangle.key2\ , self->g_workspace_H1_info[kk].pivot\ ); } printf("\nafter update. press key to continue "); //getchar(); } //if (dim) // self->g_H0_MAX = self->g_n_reduced_simplex[dim]; } void reduce_with_self_H1( \ filtration* self \ ){ int compare; int i, m; int idx; EDGE_ID count, j, k; count = 0; for (i=0; i < self->g_ws_counter; i++){ boundary_H1_ws* this_ws = self->g_workspace_H1_info + i; this_ws->flag_reduce = 0; // If the simplex has already been reduced to 0 // then continue if (this_ws->flag_empty){ this_ws->flag_append_to_complex = 0; continue; } EDGE_ID* orig = self->g_workspace_H1[i] + this_ws->original*this_ws->max_len; m = 0; while (m < i){ boundary_H1_ws* m_ws = self->g_workspace_H1_info + m; if (m_ws->flag_empty){ m++; continue; } EDGE_ID* original_m = self->g_workspace_H1[m] + m_ws->original*m_ws->max_len; orig = self->g_workspace_H1[i] + this_ws->original*this_ws->max_len; if (m_ws->pivot > this_ws->pivot){ if (m_ws->flag_red_w_complex){ this_ws->flag_append_to_complex = 0; break; } m++; continue; } if (m_ws->pivot < this_ws->pivot){ m++; continue; } if (m_ws->flag_red_w_complex){ this_ws->flag_append_to_complex = 0; //m++; //continue; break; } if (this_ws->len + m_ws->len > this_ws->max_len ){ //printf("\nReallocating inside self"); //simp_max_len_i = len_i + len_m + 1000; if (this_ws->original){ for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ self->g_workspace_H1[i][mm] = self->g_workspace_H1[i][mm + this_ws->max_len]; } this_ws->original = 0; } this_ws->max_len = this_ws->len + m_ws->len + 1000; self->g_workspace_H1[i] = (EDGE_ID*)realloc(self->g_workspace_H1[i]\ , 2*this_ws->max_len*sizeof(EDGE_ID)); orig = self->g_workspace_H1[i]; } EDGE_ID* scratch = self->g_workspace_H1[i] + (1-this_ws->original)*this_ws->max_len; // Store the result in scratch count = 0; j = 0; k = 0; while ((j < this_ws->len) && (k < m_ws->len)){ if (orig[j] < original_m[k]){ scratch[count++] = orig[j++]; } else if (orig[j] > original_m[k]){ scratch[count++] = original_m[k++]; } else{ j++; k++; } } while (j < this_ws->len){ scratch[count++] = orig[j++]; } while (k < m_ws->len){ scratch[count++] = original_m[k++]; } this_ws->len = count; this_ws->original = 1 - this_ws->original; if (!count){ this_ws->flag_append_to_complex = 0; this_ws->flag_empty = 1; break; } this_ws->pivot = scratch[this_ws->len-1]; //printf("\npivot is %d", this_ws->pivot); // Check if pivot is trivial or if it is pivot in H1 if (self->g_coH1_all_lows[this_ws->pivot].low.key1 == this_ws->pivot){ compute_boundary_triangle(self, self->g_coH1_all_lows[this_ws->pivot].low, this_ws->trivial_boundary); this_ws->R_col_idx = 0; this_ws->reduce_with_len = 3; this_ws->flag_reduce = 1; this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; break; } else{ idx = self->g_pivots_H1[this_ws->pivot]; if (idx){ this_ws->R_col_idx = idx; this_ws->reduce_with_len = self->g_R_col_idx_H1[idx+1] - self->g_R_col_idx_H1[idx]; this_ws->flag_reduce = 1; this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; break; } } //idx = self->g_pivots_H1[this_ws->pivot]; //// If the pivot is in red complex, then this has to be reduced w/ complex ////if (idx != self->g_n_reduced_simplex[self->g_dim_now]){ //if (idx){ // // this_ws->flag_red_w_complex = 1; // this_ws->flag_append_to_complex = 0; // break; //} //} m = 0; }//End of m loop } }//End of red_ws_w_self_single void* reduce_with_complex_H1(void* arg){ filtration* self = arg; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_mutex_lock(&(self->g_thread_lock)); int tid = ++self->g_thread_id; EDGE_ID *simp, *original_simp, *scratch_simp, *red_start; EDGE_ID j, k ,count; //EDGE_ID reduced_col; int i ,reduced_col ,idx; for (;;){ self->g_sleeping_threads++; if (self->g_sleeping_threads == self->g_cpu_count) pthread_cond_signal(&(self->g_start_boss)); pthread_cond_wait(&(self->g_start_workers), &(self->g_thread_lock)); if (self->g_delete_threads){ //printf("\nexiting from thread %d", tid); pthread_mutex_unlock(&(self->g_thread_lock)); pthread_exit(NULL); } self->g_sleeping_threads--; pthread_mutex_unlock(&(self->g_thread_lock)); for (i = self->g_jobs[tid - 1]; i < self->g_jobs[tid]; i++){ boundary_H1_ws* this_ws = self->g_workspace_H1_info + i; if (this_ws->flag_first){ this_ws->flag_first = 0; // Check if this is part of trivial pair if (self->g_coH1_all_lows[this_ws->pivot].low.key1 == this_ws->pivot){ compute_boundary_triangle(self\ , self->g_coH1_all_lows[this_ws->pivot].low\ , this_ws->trivial_boundary); this_ws->R_col_idx = 0; this_ws->reduce_with_len = 3; this_ws->flag_reduce = 1; } else{ idx = self->g_pivots_H1[this_ws->pivot]; if (idx){ this_ws->R_col_idx = idx; this_ws->reduce_with_len = self->g_R_col_idx_H1[idx+1] - self->g_R_col_idx_H1[idx]; this_ws->flag_reduce = 1; } } } if (this_ws->flag_empty){ // We are sure that we will exit only if there is no reduction // required with existing complex or with trivial pair this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 0; continue; } this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 1; EDGE_ID* orig = self->g_workspace_H1[i] \ + this_ws->original*this_ws->max_len; EDGE_ID* scratch = self->g_workspace_H1[i] \ + (1-this_ws->original)*this_ws->max_len; //printf("\nreducing with %d", idx); while(this_ws->flag_reduce){ //printf("\nreducing with %d", idx); //red_start = self->g_R_H1 + self->g_R_col_idx_H1[idx]; //len_a2 = self->g_R_col_idx_H1[idx+1] - self->g_R_col_idx_H1[idx]; if (this_ws->len + this_ws->reduce_with_len > this_ws->max_len){ if (this_ws->original){ for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ self->g_workspace_H1[i][mm] = self->g_workspace_H1[i][mm + this_ws->max_len]; } this_ws->original = 0; } this_ws->max_len = this_ws->len + this_ws->reduce_with_len + 1000; self->g_workspace_H1[i] = (EDGE_ID*)realloc(self->g_workspace_H1[i]\ , 2*this_ws->max_len*sizeof(EDGE_ID)); orig = self->g_workspace_H1[i]; } if (!this_ws->R_col_idx){ red_start = this_ws->trivial_boundary; } else{ red_start = self->g_R_H1 + self->g_R_col_idx_H1[this_ws->R_col_idx]; } scratch = self->g_workspace_H1[i] \ + (1-this_ws->original)*this_ws->max_len; count = 0; j = 0; k = 0; while ((j < this_ws->len) && (k < this_ws->reduce_with_len)){ if (orig[j] < red_start[k]){ scratch[count++] = orig[j++]; } else if (orig[j] > red_start[k]){ scratch[count++] = red_start[k++]; } else{ j++; k++; } } while (j < this_ws->len){ scratch[count++] = orig[j++]; } while (k < this_ws->reduce_with_len){ scratch[count++] = red_start[k++]; } this_ws->original = 1 - this_ws->original; this_ws->len = count; if (!this_ws->len){ //idx = self->g_n_reduced_simplex[self->g_dim_now]; //idx = -1; this_ws->flag_empty = 1; break; } orig = self->g_workspace_H1[i] + this_ws->original*this_ws->max_len; this_ws->pivot = orig[this_ws->len-1]; //printf("\npivot is %d", this_ws->pivot); this_ws->flag_reduce = 0; // First check if this is trivial pair if (self->g_coH1_all_lows[this_ws->pivot].low.key1 == this_ws->pivot){ compute_boundary_triangle(self\ , self->g_coH1_all_lows[this_ws->pivot].low\ , this_ws->trivial_boundary); this_ws->R_col_idx = 0; this_ws->reduce_with_len = 3; this_ws->flag_reduce = 1; } else{ idx = self->g_pivots_H1[this_ws->pivot]; if (idx){ this_ws->R_col_idx = idx; this_ws->reduce_with_len = self->g_R_col_idx_H1[idx+1] - self->g_R_col_idx_H1[idx]; this_ws->flag_reduce = 1; } } //printf("\nidx is %d", idx); } } pthread_mutex_lock(&(self->g_thread_lock)); self->g_processed_threads++; } } void update_R_H1 (filtration* self, int ws_counter){ //printf("\nupdating R H1"); boundary_H1_ws* this_ws = self->g_workspace_H1_info + ws_counter; EDGE_ID* orig = self->g_workspace_H1[ws_counter] \ + this_ws->original*this_ws->max_len; // Update R if ((self->g_R_len_H1 + this_ws->len) > self->g_R_max_len_H1){ self->g_R_max_len_H1 += 1000 + this_ws->len; self->g_R_H1 = (EDGE_ID*)realloc(self->g_R_H1, self->g_R_max_len_H1*sizeof(EDGE_ID)); } // Update R col idx self->g_R_col_idx_H1_ptr++; if (self->g_R_col_idx_H1_ptr == self->g_R_col_idx_max_len_H1 - 1){ self->g_R_col_idx_max_len_H1 += 1000; self->g_R_col_idx_H1 = (EDGE_ID*)realloc(self->g_R_col_idx_H1\ , self->g_R_col_idx_max_len_H1*sizeof(EDGE_ID)); } //if (this_ws->pivot == 12631){ // printf("\nR is stored at R_col_idx %d: ", self->g_R_col_idx_H1_ptr); // for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ // printf("%d, ", orig[mm]); // } // getchar(); //} //printf("\nAdding pivot %d at %d", this_ws->pivot, self->g_R_col_idx_H1_ptr); self->g_pivots_H1[this_ws->pivot] = self->g_R_col_idx_H1_ptr; self->g_R_col_idx_H1[self->g_R_col_idx_H1_ptr] = self->g_R_len_H1; for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ self->g_R_H1[self->g_R_len_H1++] = orig[mm]; //printf("\nadded %d", self->g_R_H1[self->g_R_len_H1 - 1]); } self->g_R_col_idx_H1[self->g_R_col_idx_H1_ptr+1] = self->g_R_len_H1; PAR birth = self->g_edge_parameter[this_ws->pivot]; PAR death = self->g_edge_parameter[this_ws->triangle.key1]; //#ifdef HOM_CYCLES if (self->g_compute_cycles){ self->g_H1_pivot_of[this_ws->pivot].coface.key1 = this_ws->triangle.key1; self->g_H1_pivot_of[this_ws->pivot].coface.key2 = this_ws->triangle.key2; //if (this_ws->pivot == 2879) //printf("\nAdding pivot %d with simplex (%d, %d)", this_ws->pivot\ // , this_ws->triangle.key1\ // , this_ws->triangle.key2\ // ); } //#endif //printf("\n%lf, %lf", birth, death); if (death != birth){ //printf("\n(%d, %d) has pivot %d at (%lf, %lf)", this_ws->triangle.key1\ // , this_ws->triangle.key2\ // , this_ws->pivot\ // , birth\ // , death\ // ); self->g_homH1_pers[self->g_homH1_pers_len].birth_edge = this_ws->pivot; self->g_homH1_pers[self->g_homH1_pers_len].death_triangle_key1 = this_ws->triangle.key1; self->g_homH1_pers[self->g_homH1_pers_len++].R_col_idx = self->g_R_col_idx_H1_ptr; if (self->g_homH1_pers_len == self->g_homH1_pers_max_len){ self->g_homH1_pers_max_len += 100; self->g_homH1_pers = (homH1_pers*)realloc(self->g_homH1_pers\ , self->g_homH1_pers_max_len*sizeof(homH1_pers)); } //if (self->g_filetype == 1){ // fprintf(self->g_homH1_pers_file, "%0.12lf, %0.12lf\n", sqrt(birth), sqrt(death)); //} //else{ // fprintf(self->g_homH1_pers_file, "%0.12lf, %0.12lf\n", birth, death); //} //for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ // // fprintf(self->g_homH1_cycles_file, "%d, %d,", self->g_edges_list[orig[mm]][0]\ // , self->g_edges_list[orig[mm]][1]); // //printf("\nadded %d", self->g_R_H1[self->g_R_len_H1 - 1]); //} // //fprintf(self->g_homH1_cycles_file, "\n"); } } void get_birth_cycle(filtration* self, EDGE_ID bo_idx){ self->g_temp_V_primary.len = 1; self->g_temp_V_primary.VV[0] = bo_idx; self->g_temp_R_birth_cycles.original = 0; self->g_temp_R_birth_cycles.RR[0] = self->g_edges_list[2*bo_idx]; self->g_temp_R_birth_cycles.RR[1] = self->g_edges_list[2*bo_idx+1]; self->g_temp_R_birth_cycles.len = 2; EDGE_ID* original_result; EDGE_ID* scratch_result; EDGE_ID j, k, count, possible_len, ro, red_simp_len, pivot; EDGE_ID* red_start; self->g_depth = 0; #ifdef ADAPTIVE_V_STORAGE self->g_store_V_for_len = 0; #endif while (self->g_temp_R_birth_cycles.len){ original_result = self->g_temp_R_birth_cycles.RR \ + (self->g_temp_R_birth_cycles.original)*self->g_temp_R_birth_cycles.max_len; pivot = original_result[self->g_temp_R_birth_cycles.len-1]; bo_idx = self->g_H0_pivot_of[pivot].coface; // FIND THE V RECURSIVELY find_V_recursively_edges(self, bo_idx, pivot); ro = (EDGE_ID)self->g_pivots_H0[pivot]; red_simp_len = self->g_R_col_indices_H0[ro+1] - \ self->g_R_col_indices_H0[ro]; red_start = self->g_R_sparse_H0 + self->g_R_col_indices_H0[ro]; // Check for overflow possible_len = self->g_temp_R_birth_cycles.len + red_simp_len; if (possible_len > self->g_temp_R_birth_cycles.max_len - 1){ if (self->g_temp_R_birth_cycles.original){ for (EDGE_ID k = 0; k < self->g_temp_R_birth_cycles.len; k++){ self->g_temp_R_birth_cycles.RR[k] =\ self->g_temp_R_birth_cycles.RR[k + self->g_temp_R_birth_cycles.max_len]; } } self->g_temp_R_birth_cycles.max_len = possible_len + 1000; self->g_temp_R_birth_cycles.RR = (EDGE_ID*)realloc(self->g_temp_R_birth_cycles.RR\ , (2*self->g_temp_R_birth_cycles.max_len)*sizeof(EDGE_ID)); original_result = self->g_temp_R_birth_cycles.RR; self->g_temp_R_birth_cycles.original = 0; } scratch_result = self->g_temp_R_birth_cycles.RR \ + (1-self->g_temp_R_birth_cycles.original)*self->g_temp_R_birth_cycles.max_len; // Reduce j = 0; k = 0; count = 0; while ((j < self->g_temp_R_birth_cycles.len) && (k < red_simp_len)){ if (original_result[j] < red_start[k]){ scratch_result[count] = original_result[j]; count = count + 1; j = j + 1; } else if (original_result[j] > red_start[k]){ scratch_result[count] = red_start[k]; count = count + 1; k = k + 1; } else{ j = j + 1; k = k + 1; } } while (j < self->g_temp_R_birth_cycles.len){ scratch_result[count++] = original_result[j++]; } while (k < red_simp_len){ scratch_result[count++] = red_start[k++]; } self->g_temp_R_birth_cycles.len = count; self->g_temp_R_birth_cycles.original = 1 - self->g_temp_R_birth_cycles.original; } //// Reduce V reduce_temp_V_H0(self); } void find_V_recursively_edges(filtration* self, EDGE_ID bo_idx, EDGE_ID bo_pivot){ #ifdef RECORD_V_USAGE self->g_H0_pivot_of[bo_pivot].V_usage++; #endif #ifdef ADAPTIVE_V_STORAGE if (self->g_H0_pivot_of[bo_pivot].V_len){ //printf("\nUsing stored cycle for %d", bo_idx); if ((self->g_temp_V_primary.len + self->g_H0_pivot_of[bo_pivot].V_len) > self->g_temp_V_primary.max_len - 1){ self->g_temp_V_primary.max_len = self->g_temp_V_primary.len + self->g_H0_pivot_of[bo_pivot].V_len + 1000; self->g_temp_V_primary.VV = (EDGE_ID*)realloc(self->g_temp_V_primary.VV\ , self->g_temp_V_primary.max_len*sizeof(EDGE_ID)); } for (EDGE_ID mm = 0; mm < self->g_H0_pivot_of[bo_pivot].V_len; mm++){ self->g_temp_V_primary.VV[self->g_temp_V_primary.len++] =\ self->g_H0_pivot_of[bo_pivot].VV[mm]; } return; } #endif EDGE_ID res_max_len = 100; EDGE_ID* result = (EDGE_ID*)malloc((2*res_max_len)*sizeof(EDGE_ID)); int res_original = 0; EDGE_ID* original_result; EDGE_ID* scratch_result; EDGE_ID res_len = 2; result[0] = self->g_edges_list[2*bo_idx]; result[1] = self->g_edges_list[2*bo_idx+1]; EDGE_ID possible_len; EDGE_ID* red_start; EDGE_ID red_simp_len; EDGE_ID ro; EDGE_ID j, k, count; EDGE_ID pivot; // RECORD THIS IN REDUCTION OPERATION for e_o self->g_temp_V_primary.VV[self->g_temp_V_primary.len++] = bo_idx; // Check for overflow if (self->g_temp_V_primary.len == self->g_temp_V_primary.max_len){ //printf("\nReallocating"); //getchar(); self->g_temp_V_primary.max_len += 100; self->g_temp_V_primary.VV = (EDGE_ID*)realloc(self->g_temp_V_primary.VV\ , self->g_temp_V_primary.max_len*sizeof(EDGE_ID)); } while(res_len != 0){ #ifdef ADAPTIVE_V_STORAGE self->g_depth++; #endif original_result = result + (res_original*res_max_len); scratch_result = result + ((1-res_original)*res_max_len); pivot = original_result[res_len-1]; // The new pivot is pivot of R(bo_idx) bo_idx = self->g_H0_pivot_of[pivot].coface; ro = (EDGE_ID)self->g_pivots_H0[pivot]; red_simp_len = self->g_R_col_indices_H0[ro+1] - \ self->g_R_col_indices_H0[ro]; red_start = self->g_R_sparse_H0 + self->g_R_col_indices_H0[ro]; // Check for overflow possible_len = res_len + red_simp_len; if (possible_len > res_max_len - 1){ if (res_original){ for (k = 0; k < res_len; k++){ result[k] = result[k + res_max_len]; } } res_max_len = possible_len + 1000; result = (EDGE_ID*)realloc(result, (2*res_max_len)*sizeof(EDGE_ID)); original_result = result; scratch_result = result + res_max_len; res_original = 0; } // Reduce j = 0; k = 0; count = 0; while ((j < res_len) && (k < red_simp_len)){ if (original_result[j] < red_start[k]){ scratch_result[count] = original_result[j]; count = count + 1; j = j + 1; } else if (original_result[j] > red_start[k]){ scratch_result[count] = red_start[k]; count = count + 1; k = k + 1; } else{ j = j + 1; k = k + 1; } } while (j < res_len){ scratch_result[count++] = original_result[j++]; } while (k < red_simp_len){ scratch_result[count++] = red_start[k++]; } res_len = count; res_original = 1 - res_original; if (res_len != 0){ find_V_recursively_edges(self, bo_idx, pivot); } } #ifndef RECORD_V_USAGE self->g_H0_pivot_of[bo_pivot].V_usage++; #endif #ifdef ADAPTIVE_V_STORAGE if ((self->g_H0_pivot_of[bo_pivot].V_usage > self->g_cycle_usage_thresh)\ &&(!self->g_H0_pivot_of[bo_pivot].V_stored)){ self->g_store_V_for[self->g_store_V_for_len++] = bo_pivot; if (self->g_store_V_for_len == self->g_store_V_for_max_len){ self->g_store_V_for_max_len += 100; self->g_store_V_for = (EDGE_ID*)realloc(self->g_store_V_for\ , self->g_store_V_for_max_len*sizeof(EDGE_ID)); } } #endif free(result); } void compute_H2_homology_cycles(filtration* self){ /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // // STEP H2.1: Find homology now for the tetrahedrons (H2) // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// if (!self->g_suppress_output){ printf("\n\n---------------"); printf("\nComputing H2..."); printf("\n---------------\n"); } struct timespec start_wall_clock, finish_wall_clock; clock_gettime(CLOCK_MONOTONIC, &(self->g_start_wall_clock)); self->g_R_max_len_H2 = 100; self->g_R_H2 = (simplex*)malloc(self->g_R_max_len_H2*sizeof(simplex)); self->g_R_len_H2 = 0; self->g_R_col_idx_max_len_H2 = 100; self->g_R_col_idx_H2 = (EDGE_ID*)malloc(self->g_R_col_idx_max_len_H2*sizeof(EDGE_ID)); self->g_R_col_idx_H2_ptr = 0; self->g_workspace_size = 1000; self->g_ws_pre_alloc = 1000; // Initialize ws counter self->g_ws_counter = 0; // H1 workspace structures self->g_workspace_H2 = (simplex**)malloc(self->g_workspace_size*sizeof(simplex*)); // H1 workspace info self->g_workspace_H2_info = (boundary_H2_ws*)malloc(self->g_workspace_size*sizeof(boundary_H2_ws)); for (int i = 0; i < self->g_workspace_size; i++){ self->g_workspace_H2_info[i].max_len = self->g_ws_pre_alloc; self->g_workspace_H2[i] = (simplex*)malloc(2*self->g_workspace_H2_info[i].max_len*sizeof(simplex)); self->g_workspace_H2_info[i].trivial_boundary = (simplex*)malloc(4*sizeof(simplex)); } // Pivots self->g_H2_pivots = (H2_pivots**)malloc(self->g_n_valid_edges*sizeof(H2_pivots*)); self->g_H2_pivots_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); self->g_H2_pivots_max_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); for (EDGE_ID mm = 0; mm < self->g_n_valid_edges; mm++){ self->g_H2_pivots_max_len[mm] = 5; self->g_H2_pivots[mm] = (H2_pivots*)malloc(self->g_H2_pivots_max_len[mm]*sizeof(H2_pivots)); } // Convenient info for pers pairs self->g_homH2_pers_len = 0; self->g_homH2_pers_max_len = 100; self->g_homH2_pers = (homH2_pers*)malloc(self->g_homH2_pers_max_len*sizeof(homH2_pers)); // Temporary space for birth cycles self->g_temp_V_H2_primary.max_len = 10; self->g_temp_V_H2_primary.VV = (simplex*)malloc(self->g_temp_V_H2_primary.max_len*sizeof(simplex)); self->g_temp_V_H2_primary.len = 0; // Temporary space for birth cycles self->g_temp_R_H2_birth_cycles.max_len = 100; self->g_temp_R_H2_birth_cycles.RR = (EDGE_ID*)malloc(2*self->g_temp_R_H2_birth_cycles.max_len*sizeof(EDGE_ID)); self->g_temp_R_H2_birth_cycles.original = 0; self->g_temp_R_H2_birth_cycles.len = 0; #ifdef ADAPTIVE_V_STORAGE // Create pointers to store V for (EDGE_ID mm = 0; mm < self->g_n_valid_edges; mm++){ self->g_H1_pivot_of[mm].V_usage = 0; self->g_H1_pivot_of[mm].V_stored = 0; self->g_H1_pivot_of[mm].V_len = 0; self->g_H1_pivot_of[mm].VV = NULL; } // Create pointers to store V per extraction call self->g_store_V_for_len = 0; self->g_store_V_for_max_len = 10; self->g_store_V_for = (EDGE_ID*)malloc(self->g_store_V_for_max_len*sizeof(EDGE_ID)); #endif //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ self->g_all_V_stored_num = 0; self->g_all_V_stored_max_num = 10; self->g_all_V_H1_stored = (cyc_info_H2*)malloc(self->g_all_V_stored_max_num*sizeof(cyc_info_H2)); } //#endif //////////////////////////////////////////////////////////////// // // Allocate jobs for parallel H1 // //////////////////////////////////////////////////////////////// self->g_jobs = (int*)malloc((self->g_cpu_count + 1)*sizeof(int)); allocate_jobs(self, self->g_workspace_size); self->g_threads = (pthread_t *)malloc(self->g_cpu_count*sizeof(pthread_t)); int rtn; if ((rtn = pthread_mutex_init(&(self->g_thread_lock), NULL)) !=0) fprintf(stderr, "pthread_mutex_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_boss), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); if ((rtn = pthread_cond_init(&(self->g_start_workers), NULL)) !=0) fprintf(stderr, "pthread_cond_init %s", strerror(rtn)), exit(-1); // Initialize thread creation self->g_thread_id = 0; self->g_sleeping_threads = 0; self->g_delete_threads = 0; for (int i = 0; i < self->g_cpu_count; i++){ if ((rtn = pthread_create( \ &(self->g_threads[i]) \ , NULL \ , reduce_with_complex_H2 \ , (void*)self)!= 0)) fprintf(stderr, "pthread_create %d", rtn), exit(-1); } // Wait for threads to be initialized pthread_mutex_lock(&(self->g_thread_lock)); while(self->g_sleeping_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ , &(self->g_thread_lock)); } //////////////////////////////// H2_preprocess* temp_tetra = (H2_preprocess*)malloc(self->g_n_valid_edges*sizeof(H2_preprocess)); EDGE_ID temp_tetra_len = 0; int ccounter = 0; self->g_new_debug2 = 0; EDGE_ID o_cd; self->g_ws_counter = 0; for (EDGE_ID o_ab = 0; o_ab < self->g_n_valid_edges; o_ab++){ if (!self->g_H2_cohom_pivots_len[o_ab]){ continue; } for (VERT_ID mm = 0; mm < self->g_H2_cohom_pivots_len[o_ab]; mm++){ o_cd = self->g_H2_cohom_pivots[o_ab][mm].key2; // Workspace attributes boundary_H2_ws* this_ws = self->g_workspace_H2_info + self->g_ws_counter; // Initially, the original is at 0 this_ws->original = 0; this_ws->flag_first = 1; // Parallel control flags this_ws->flag_empty = 0; this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 1; this_ws->tetrahedron.key1 = o_ab; this_ws->tetrahedron.key2 = o_cd; // Initial length of boundary this_ws->len = 4; compute_boundary_tetra(self, this_ws->tetrahedron, self->g_workspace_H2[self->g_ws_counter]); this_ws->pivot = self->g_workspace_H2[self->g_ws_counter][3]; self->g_ws_counter++; if (self->g_ws_counter == self->g_workspace_size){ reduce_ws_H2(self); } } } // Reduction of final batch while (self->g_ws_counter){ allocate_jobs(self, self->g_ws_counter); reduce_ws_H2(self); } clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_computeH2 = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_computeH2 += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; if (!self->g_suppress_output){ printf("\nComputed H2."); } //////////////////////// // HOMOLOGY CYCLES //////////////////////// clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); FILE* fp2 = fopen(self->g_homH2_cycles_file, "w"); PAR birth, death; self->g_n_H1_stored_V = 0; // Go over the pers pairs of features that died and compute the cycles for (EDGE_ID mm = 0; mm < self->g_homH2_pers_len; mm++){ self->g_n_H2_birth_cycles++; //printf("\nFinding cycle for (%d, %d)", self->g_homH2_pers[mm].birth_simplex.key1\ // , self->g_homH2_pers[mm].birth_simplex.key2); //getchar(); if (self->g_filetype == 1){ birth = sqrt(self->g_edge_parameter[self->g_homH2_pers[mm].birth_simplex.key1]); death = sqrt(self->g_edge_parameter[self->g_homH2_pers[mm].death_edge]); } else{ birth = self->g_edge_parameter[self->g_homH2_pers[mm].birth_simplex.key1]; death = self->g_edge_parameter[self->g_homH2_pers[mm].death_edge]; } fprintf(fp2, "%lf, %lf", birth, death); fprintf(fp2, "\nhomology cycle"); for (EDGE_ID bb = self->g_R_col_idx_H2[self->g_homH2_pers[mm].R_col_idx]\ ; bb < self->g_R_col_idx_H2[self->g_homH2_pers[mm].R_col_idx + 1]\ ; bb++){ fprintf(fp2, ", %d, %d, %d", self->g_edges_list[2*self->g_R_H2[bb].key1]\ , self->g_edges_list[2*self->g_R_H2[bb].key1+1]\ , self->g_R_H2[bb].key2\ ); } // Always write the birth cycles to file for now fprintf(fp2, "\nbirth cycle"); //printf("\nGetting birth cycle %d out of %d", mm, self->g_homH1_pers_len); //getchar(); #ifdef ADAPTIVE_V_STORAGE self->g_store_V_for_len = 0; #endif //printf("\nGetting void"); get_birth_void(self, self->g_homH2_pers[mm].birth_simplex); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ //self->g_all_V_stored_len[self->g_all_V_stored_num] = self->g_temp_V_H2_primary.len; //self->g_all_V_H1_stored[self->g_all_V_stored_num] =\ // (simplex*)malloc(self->g_temp_V_H2_primary.len*sizeof(simplex)); self->g_all_V_H1_stored[self->g_all_V_stored_num].boundary =\ (simplex*)malloc(self->g_temp_V_H2_primary.len*sizeof(simplex)); self->g_all_V_H1_stored[self->g_all_V_stored_num].len = self->g_temp_V_H2_primary.len; self->g_all_V_H1_stored[self->g_all_V_stored_num].perspair[0] = birth; self->g_all_V_H1_stored[self->g_all_V_stored_num].perspair[1] = death; self->g_all_V_H1_stored[self->g_all_V_stored_num].updated_birth = birth; } //#endif for (EDGE_ID nn = 0; nn < self->g_temp_V_H2_primary.len; nn++){ fprintf(fp2, ", %d, %d, %d", self->g_edges_list[2*self->g_temp_V_H2_primary.VV[nn].key1]\ , self->g_edges_list[2*self->g_temp_V_H2_primary.VV[nn].key1+1]\ , self->g_temp_V_H2_primary.VV[nn].key2\ ); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ self->g_all_V_H1_stored[self->g_all_V_stored_num].boundary[nn] = self->g_temp_V_H2_primary.VV[nn]; } //#endif } fprintf(fp2, "\n"); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ self->g_all_V_stored_num++; if (self->g_all_V_stored_num == self->g_all_V_stored_max_num){ self->g_all_V_stored_max_num += 100; self->g_all_V_H1_stored = (cyc_info_H2*)realloc(self->g_all_V_H1_stored\ , self->g_all_V_stored_max_num*sizeof(cyc_info_H2)); //self->g_all_V_stored_len = (EDGE_ID*)realloc(self->g_all_V_stored_len\ // , self->g_all_V_stored_max_num*sizeof(EDGE_ID)); } } //#endif #ifdef ADAPTIVE_V_STORAGE //printf("\nPress key to store V at line 10412"); //getchar(); store_V_H1(self); //printf("\nstored V at line 10412. Pres key to continue."); //getchar(); #endif } // Go over the pers pairs of undead features and compute the birth cycles for (EDGE_ID mm = 0; mm < self->g_H2_undead_ptr; mm++){ self->g_n_H2_birth_cycles++; if (self->g_filetype == 1){ birth = sqrt(self->g_edge_parameter[self->g_H2_undead[mm].key1]); } else{ birth = self->g_edge_parameter[self->g_H2_undead[mm].key1]; } fprintf(fp2, "%lf, -1", birth); #ifdef ADAPTIVE_V_STORAGE self->g_store_V_for_len = 0; #endif get_birth_void(self, self->g_H2_undead[mm]); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ //self->g_all_V_stored_len[self->g_all_V_stored_num] = self->g_temp_V_H2_primary.len; self->g_all_V_H1_stored[self->g_all_V_stored_num].boundary =\ (simplex*)malloc(self->g_temp_V_H2_primary.len*sizeof(simplex)); self->g_all_V_H1_stored[self->g_all_V_stored_num].len = self->g_temp_V_H2_primary.len; self->g_all_V_H1_stored[self->g_all_V_stored_num].perspair[0] = birth; self->g_all_V_H1_stored[self->g_all_V_stored_num].perspair[1] = -1; self->g_all_V_H1_stored[self->g_all_V_stored_num].updated_birth = birth; } //#endif fprintf(fp2, "\nbirth cycle"); for (EDGE_ID nn = 0; nn < self->g_temp_V_H2_primary.len; nn++){ fprintf(fp2, ", %d, %d, %d", self->g_edges_list[2*self->g_temp_V_H2_primary.VV[nn].key1]\ , self->g_edges_list[2*self->g_temp_V_H2_primary.VV[nn].key1+1]\ , self->g_temp_V_H2_primary.VV[nn].key2\ ); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ self->g_all_V_H1_stored[self->g_all_V_stored_num].boundary[nn] = self->g_temp_V_H2_primary.VV[nn]; } //#endif } fprintf(fp2, "\n"); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ self->g_all_V_stored_num++; if (self->g_all_V_stored_num == self->g_all_V_stored_max_num){ self->g_all_V_stored_max_num += 100; //self->g_all_V_H1_stored = (simplex**)realloc(self->g_all_V_H1_stored\ // , self->g_all_V_stored_max_num*sizeof(simplex*)); self->g_all_V_H1_stored = (cyc_info_H2*)realloc(self->g_all_V_H1_stored\ , self->g_all_V_stored_max_num*sizeof(cyc_info_H2)); //self->g_all_V_stored_len = (EDGE_ID*)realloc(self->g_all_V_stored_len\ // , self->g_all_V_stored_max_num*sizeof(EDGE_ID)); } } //#endif #ifdef ADAPTIVE_V_STORAGE store_V_H1(self); #endif } if (!self->g_suppress_output){ printf("\nComputed birth cycles."); } //getchar(); ///////////////////////// // Cancel the threads used in getting next during reduction ///////////////////////// self->g_delete_threads = 1; pthread_cond_broadcast(&(self->g_start_workers)); pthread_mutex_unlock(&(self->g_thread_lock)); for (int i = 0; i < self->g_cpu_count; i++){ pthread_join(self->g_threads[i], NULL); } free(self->g_jobs); free(self->g_threads); for (int i = 0; i < self->g_workspace_size; i++){ free(self->g_workspace_H2_info[i].trivial_boundary); free(self->g_workspace_H2[i]); } free(self->g_workspace_H2); free(self->g_workspace_H2_info); free(self->g_R_H2); free(self->g_R_col_idx_H2); free(self->g_H2_pivots); free(self->g_homH2_pers); free(self->g_temp_V_H2_primary.VV); free(self->g_temp_R_H2_birth_cycles.RR); free(self->g_R_H1); free(self->g_R_col_idx_H1); free(self->g_pivots_H1); #ifdef ADAPTIVE_V_STORAGE free(self->g_store_V_for); #ifdef RECORD_V_USAGE FILE* fp3 = fopen(self->g_V_H1_usage_file, "w"); #endif for (EDGE_ID mm = 0; mm < self->g_n_valid_edges; mm++){ if (self->g_H1_pivot_of[mm].V_len){ #ifdef RECORD_V_USAGE fprintf(fp3, "%d, %d\n"\ , self->g_H1_pivot_of[mm].V_usage\ , self->g_H1_pivot_of[mm].V_depth); #endif free(self->g_H1_pivot_of[mm].VV); } } #ifdef RECORD_V_USAGE fclose(fp3); #endif #endif //#ifdef HOM_CYCLES free(self->g_H1_pivot_of); clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_H2cycles = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_H2cycles += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; //#endif if (!self->g_suppress_output){ printf("\nQUITTING H2 cycle computation"); } //getchar(); //#ifdef MINIMIZE_BIRTH_CYCLES if (self->g_reduce_cyc_lengths){ if (!self->g_suppress_output){ printf("\nMinimizing birth cycles..."); } //getchar(); clock_gettime(CLOCK_MONOTONIC, &start_wall_clock); minimize_birth_cycles_H1_v2(self\ , self->g_all_V_H1_stored\ , self->g_all_V_stored_num\ , self->g_minimal_V_H1_file\ , self->g_V_H1_birthcyc_lens_file\ , self->g_minimal_V_H1_birthcyc_lens_file\ ); clock_gettime(CLOCK_MONOTONIC, &finish_wall_clock); self->g_timer_minimize_H2cycles = (finish_wall_clock.tv_sec - start_wall_clock.tv_sec); self->g_timer_minimize_H2cycles += (finish_wall_clock.tv_nsec - start_wall_clock.tv_nsec) / 1000000000.0; } //#endif } void reduce_ws_H2(filtration* self){ //if (self->g_new_debug2){ //printf("\nBEFORE parallel."); //for (int kk = 0; kk < self->g_ws_counter; kk++){ // // printf("\n%d has triangle (%d, %d) with pivot (%d, %d) and reduce_with %p", kk\ // , self->g_workspace_H2_info[kk].tetrahedron.key1\ // , self->g_workspace_H2_info[kk].tetrahedron.key2\ // , self->g_workspace_H2_info[kk].pivot.key1\ // , self->g_workspace_H2_info[kk].pivot.key2\ // , self->g_workspace_H2_info[kk].reduce_with\ // ); //} //getchar(); //} self->g_processed_threads = 0; //printf("\npress key to reduce with complex"); //getchar(); pthread_cond_broadcast(&(self->g_start_workers)); while (self->g_processed_threads != self->g_cpu_count){ pthread_cond_wait(&(self->g_start_boss) \ ,&(self->g_thread_lock)); } //printf("\npress key to reduce with self"); //getchar(); //if (self->g_new_debug2){ // for (int kk = 0; kk < self->g_ws_counter; kk++){ // // printf("\n%d has triangle (%d, %d) with pivot %d", kk\ // , self->g_workspace_H1_info[kk].triangle.key1\ // , self->g_workspace_H1_info[kk].triangle.key2\ // , self->g_workspace_H1_info[kk].pivot\ // ); // } // printf("\nafter parallel. press key to start serial"); // //getchar(); //} reduce_with_self_H2( \ self \ ); //printf("\nAFTER SERIAL parallel."); //for (int kk = 0; kk < self->g_ws_counter; kk++){ // // printf("\n%d has triangle (%d, %d) with pivot (%d, %d) and reduce_with %p", kk\ // , self->g_workspace_H2_info[kk].tetrahedron.key1\ // , self->g_workspace_H2_info[kk].tetrahedron.key2\ // , self->g_workspace_H2_info[kk].pivot.key1\ // , self->g_workspace_H2_info[kk].pivot.key2\ // , self->g_workspace_H2_info[kk].reduce_with\ // ); //} //if (self->g_new_debug2){ // for (int kk = 0; kk < self->g_ws_counter; kk++){ // // printf("\n%d has triangle (%d, %d) with pivot %d", kk\ // , self->g_workspace_H1_info[kk].triangle.key1\ // , self->g_workspace_H1_info[kk].triangle.key2\ // , self->g_workspace_H1_info[kk].pivot\ // ); // } // printf("\nafter serial. press key to update "); // //getchar(); //} int count_valid = 0; for (int ws_counter=0; ws_counter < self->g_ws_counter; ws_counter++){ if (self->g_workspace_H2_info[ws_counter].flag_append_to_complex){ update_R_H2(self \ , ws_counter\ ); continue; } //if (!self->g_workspace_H1_info[ws_counter].len){continue;} if (self->g_workspace_H2_info[ws_counter].flag_empty){ continue; } // Swap R simplex* temp = self->g_workspace_H2[count_valid]; self->g_workspace_H2[count_valid] = self->g_workspace_H2[ws_counter]; self->g_workspace_H2[ws_counter] = temp; // Swap R info boundary_H2_ws temp2 = self->g_workspace_H2_info[count_valid]; self->g_workspace_H2_info[count_valid] = self->g_workspace_H2_info[ws_counter]; self->g_workspace_H2_info[ws_counter] = temp2; // At this point, this has to be a non-zero column self->g_workspace_H2_info[count_valid].flag_empty = 0; count_valid += 1; } self->g_ws_counter = count_valid; //printf("\nAFTER UPDATE ."); //for (int kk = 0; kk < self->g_ws_counter; kk++){ // // printf("\n%d has triangle (%d, %d) with pivot (%d, %d)", kk\ // , self->g_workspace_H2_info[kk].tetrahedron.key1\ // , self->g_workspace_H2_info[kk].tetrahedron.key2\ // , self->g_workspace_H2_info[kk].pivot.key1\ // , self->g_workspace_H2_info[kk].pivot.key2\ // ); //} //if (self->g_new_debug2){ // for (int kk = 0; kk < self->g_ws_counter; kk++){ // // printf("\n%d has triangle (%d, %d) with pivot %d", kk\ // , self->g_workspace_H1_info[kk].triangle.key1\ // , self->g_workspace_H1_info[kk].triangle.key2\ // , self->g_workspace_H1_info[kk].pivot\ // ); // } // printf("\nafter update. press key to continue "); // //getchar(); //} //if (dim) // self->g_H0_MAX = self->g_n_reduced_simplex[dim]; } void reduce_with_self_H2( \ filtration* self \ ){ int compare; int i, m; int idx; EDGE_ID count, j, k; for (i=0; i < self->g_ws_counter; i++){ boundary_H2_ws* this_ws = self->g_workspace_H2_info + i; this_ws->flag_reduce = 0; // If the simplex has already been reduced to 0 // then continue if (this_ws->flag_empty){ this_ws->flag_append_to_complex = 0; continue; } simplex* orig = self->g_workspace_H2[i] + this_ws->original*this_ws->max_len; m = 0; while (m < i){ boundary_H2_ws* m_ws = self->g_workspace_H2_info + m; if (m_ws->flag_empty){ m++; continue; } simplex* original_m = self->g_workspace_H2[m] + m_ws->original*m_ws->max_len; orig = self->g_workspace_H2[i] + this_ws->original*this_ws->max_len; int compare; if (m_ws->pivot.key1 < this_ws->pivot.key1) compare = 1; else if (m_ws->pivot.key1 > this_ws->pivot.key1) compare = 0; else{ if (m_ws->pivot.key2 < this_ws->pivot.key2) compare = 1; else if (m_ws->pivot.key2 > this_ws->pivot.key2) compare = 0; else compare = -1; } //if (m_ws->pivot > this_ws->pivot){ if (compare == 0){ if (m_ws->flag_red_w_complex){ this_ws->flag_append_to_complex = 0; break; } m++; continue; } //if (m_ws->pivot < this_ws->pivot){ if (compare == 1){ m++; continue; } if (m_ws->flag_red_w_complex){ this_ws->flag_append_to_complex = 0; //m++; //continue; break; } if (this_ws->len + m_ws->len > this_ws->max_len ){ //printf("\nReallocating inside self"); //simp_max_len_i = len_i + len_m + 1000; if (this_ws->original){ for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ self->g_workspace_H2[i][mm] = self->g_workspace_H2[i][mm + this_ws->max_len]; } this_ws->original = 0; } this_ws->max_len = this_ws->len + m_ws->len + 1000; self->g_workspace_H2[i] = (simplex*)realloc(self->g_workspace_H2[i]\ , 2*this_ws->max_len*sizeof(simplex)); orig = self->g_workspace_H2[i]; } simplex* scratch = self->g_workspace_H2[i] + (1-this_ws->original)*this_ws->max_len; // Store the result in scratch count = 0; j = 0; k = 0; while ((j < this_ws->len) && (k < m_ws->len)){ if (orig[j].key1 < original_m[k].key1) compare = 1; else if (orig[j].key1 > original_m[k].key1) compare = 0; else{ if (orig[j].key2 < original_m[k].key2) compare = 1; else if (orig[j].key2 > original_m[k].key2) compare = 0; else compare = -1; } //if (orig[j] < original_m[k]){ if (compare == 1){ scratch[count++] = orig[j++]; } //else if (orig[j] > original_m[k]){ else if (compare == 0){ scratch[count++] = original_m[k++]; } else{ j++; k++; } } while (j < this_ws->len){ scratch[count++] = orig[j++]; } while (k < m_ws->len){ scratch[count++] = original_m[k++]; } this_ws->len = count; this_ws->original = 1 - this_ws->original; if (!count){ this_ws->flag_append_to_complex = 0; this_ws->flag_empty = 1; break; } this_ws->pivot = scratch[this_ws->len-1]; coboundary_H2 temp; temp.triangle.key1 = this_ws->pivot.key1; temp.triangle.key2 = this_ws->pivot.key2; find_H2_cohom_low(self, &temp); // Check if pivot is trivial or if it is pivot in H2 // To check trivial, check if maximum triangle in low of cob of triangle is triangle if ((temp.low.key1 == temp.triangle.key1)\ &&(self->g_edges_list[2*temp.low.key2+1] == temp.triangle.key2)){ // In which case, reduce with boundary of temp.low compute_boundary_tetra(self, temp.low, this_ws->trivial_boundary); this_ws->R_col_idx = 0; this_ws->reduce_with_len = 4; this_ws->flag_reduce = 1; this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; break; } else{ if (self->g_H2_pivots_len[this_ws->pivot.key1]){ EDGE_ID idx = search_H2_pivots(self->g_H2_pivots[this_ws->pivot.key1]\ , 0\ , self->g_H2_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges\ ); if (idx != self->g_n_valid_edges){ //this_ws->flag_red_w_trivial = 0; this_ws->R_col_idx = self->g_H2_pivots[this_ws->pivot.key1][idx].col_idx; this_ws->reduce_with_len = self->g_R_col_idx_H2[this_ws->R_col_idx+1] -\ self->g_R_col_idx_H2[this_ws->R_col_idx]; this_ws->flag_reduce = 1; this_ws->flag_red_w_complex = 1; this_ws->flag_append_to_complex = 0; break; } } } //} m = 0; }//End of m loop } }//End of red_ws_w_self_single void* reduce_with_complex_H2(void* arg){ filtration* self = arg; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_mutex_lock(&(self->g_thread_lock)); int tid = ++self->g_thread_id; simplex *red_start; EDGE_ID j, k ,count; for (;;){ self->g_sleeping_threads++; if (self->g_sleeping_threads == self->g_cpu_count) pthread_cond_signal(&(self->g_start_boss)); pthread_cond_wait(&(self->g_start_workers), &(self->g_thread_lock)); if (self->g_delete_threads){ //printf("\nexiting from thread %d", tid); pthread_mutex_unlock(&(self->g_thread_lock)); pthread_exit(NULL); } self->g_sleeping_threads--; pthread_mutex_unlock(&(self->g_thread_lock)); for (int i = self->g_jobs[tid - 1]; i < self->g_jobs[tid]; i++){ boundary_H2_ws* this_ws = self->g_workspace_H2_info + i; if (this_ws->flag_empty){ // We are sure that we will exit only if there is no reduction // required with existing complex or with trivial pair this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 0; continue; } if (this_ws->flag_first){ //if ((this_ws->tetrahedron.key1 == self->g_debug_tetra.key1)\ // &&(this_ws->tetrahedron.key2 == self->g_debug_tetra.key2)) //{ // printf("\nProcessing tetra: (%d, %d) first pivot is (%d, %d)"\ // ,self->g_debug_tetra.key1\ // ,self->g_debug_tetra.key2\ // ,this_ws->pivot.key1\ // ,this_ws->pivot.key2\ // ); // //} this_ws->flag_first = 0; coboundary_H2 temp; temp.triangle.key1 = this_ws->pivot.key1; temp.triangle.key2 = this_ws->pivot.key2; find_H2_cohom_low(self, &temp); this_ws->flag_reduce = 0; // Check if pivot is trivial or if it is pivot in H2 // To check trivial, check if maximum triangle in low of cob of triangle is triangle if ((temp.low.key1 == temp.triangle.key1)\ &&(self->g_edges_list[2*temp.low.key2+1] == temp.triangle.key2)){ // In which case, reduce with boundary of temp.low compute_boundary_tetra(self, temp.low, this_ws->trivial_boundary); this_ws->R_col_idx = 0; this_ws->reduce_with_len = 4; this_ws->flag_reduce = 1; } else{ if (self->g_H2_pivots_len[this_ws->pivot.key1]){ EDGE_ID idx = search_H2_pivots(self->g_H2_pivots[this_ws->pivot.key1]\ , 0\ , self->g_H2_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges\ ); if (idx != self->g_n_valid_edges){ //this_ws->flag_red_w_trivial = 0; this_ws->R_col_idx = self->g_H2_pivots[this_ws->pivot.key1][idx].col_idx; //this_ws->reduce_with = self->g_R_H2 + self->g_R_col_idx_H2[R_col_idx]; this_ws->reduce_with_len = self->g_R_col_idx_H2[this_ws->R_col_idx+1] -\ self->g_R_col_idx_H2[this_ws->R_col_idx]; this_ws->flag_reduce = 1; } } } } //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\npivot before reduction is (%d, %d)"\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); //} this_ws->flag_red_w_complex = 0; this_ws->flag_append_to_complex = 1; //simplex* orig = self->g_workspace_H2[i] \ // + this_ws->original*this_ws->max_len; //simplex* scratch = self->g_workspace_H2[i] \ // + (1-this_ws->original)*this_ws->max_len; //printf("\nreducing with %d", idx); while(this_ws->flag_reduce){ simplex* orig = self->g_workspace_H2[i] + this_ws->original*this_ws->max_len; if ( this_ws->len + this_ws->reduce_with_len > this_ws->max_len){ //printf("\nREALLOCATING"); if (this_ws->original){ //printf("\nCOPYING"); for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ self->g_workspace_H2[i][mm] = self->g_workspace_H2[i][mm + this_ws->max_len]; } this_ws->original = 0; } this_ws->max_len = this_ws->len + this_ws->reduce_with_len + 1000; self->g_workspace_H2[i] = (simplex*)realloc(self->g_workspace_H2[i]\ , 2*this_ws->max_len*sizeof(simplex)); orig = self->g_workspace_H2[i]; } simplex* scratch = self->g_workspace_H2[i] \ + (1-this_ws->original)*this_ws->max_len; if (!this_ws->R_col_idx){ //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nreducing with trivial boundary "\ // ); //} red_start = this_ws->trivial_boundary; } else{ //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nreducing with red complex "\ // ); //} red_start = self->g_R_H2 + self->g_R_col_idx_H2[this_ws->R_col_idx]; } //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nReducing "); // for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ // printf("(%d, %d), "\ // ,orig[mm].key1\ // ,orig[mm].key2\ // ); // } // printf("\nwith "); // for (EDGE_ID mm = 0; mm < this_ws->reduce_with_len; mm++){ // printf("(%d, %d), "\ // ,red_start[mm].key1\ // ,red_start[mm].key2\ // ); // } //} count = 0; j = 0; k = 0; int compare; while ((j < this_ws->len) && (k < this_ws->reduce_with_len)){ if (orig[j].key1 < red_start[k].key1) compare = 1; else if (orig[j].key1 > red_start[k].key1) compare = 0; else{ if (orig[j].key2 < red_start[k].key2) compare = 1; else if (orig[j].key2 > red_start[k].key2) compare = 0; else compare = -1; } if (compare == 1){ scratch[count++] = orig[j++]; } else if (compare == 0){ scratch[count++] = red_start[k++]; } else{ j++; k++; } } while (j < this_ws->len){ scratch[count++] = orig[j++]; } while (k < this_ws->reduce_with_len){ scratch[count++] = red_start[k++]; } this_ws->original = 1 - this_ws->original; this_ws->len = count; //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nAfter reduction "); // for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ // printf("(%d, %d), "\ // ,scratch[mm].key1\ // ,scratch[mm].key2\ // ); // } //} if (!this_ws->len){ //idx = self->g_n_reduced_simplex[self->g_dim_now]; //idx = -1; this_ws->flag_empty = 1; break; } //else{ this_ws->pivot = scratch[this_ws->len-1]; //printf("\nNew pivot is (%d, %d)"\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); // Check trivial pers pair //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\npivot after reduction is (%d, %d)"\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); // getchar(); //} coboundary_H2 temp; temp.triangle.key1 = this_ws->pivot.key1; temp.triangle.key2 = this_ws->pivot.key2; find_H2_cohom_low(self, &temp); this_ws->flag_reduce = 0; // Check if pivot is trivial or if it is pivot in H2 // To check trivial, check if maximum triangle in low of cob of triangle is triangle if ((temp.low.key1 == temp.triangle.key1)\ &&(self->g_edges_list[2*temp.low.key2+1] == temp.triangle.key2)){ // In which case, reduce with boundary of temp.low //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nreducing with trivial"); //} compute_boundary_tetra(self, temp.low, this_ws->trivial_boundary); //this_ws->reduce_with = this_ws->trivial_boundary; this_ws->R_col_idx = 0; this_ws->reduce_with_len = 4; this_ws->flag_reduce = 1; } else{ if (self->g_H2_pivots_len[this_ws->pivot.key1]){ EDGE_ID idx = search_H2_pivots(self->g_H2_pivots[this_ws->pivot.key1]\ , 0\ , self->g_H2_pivots_len[this_ws->pivot.key1] - 1\ , this_ws->pivot.key2 \ , self->g_n_valid_edges\ ); if (idx != self->g_n_valid_edges){ //this_ws->flag_red_w_trivial = 0; this_ws->R_col_idx = self->g_H2_pivots[this_ws->pivot.key1][idx].col_idx; this_ws->reduce_with_len = self->g_R_col_idx_H2[this_ws->R_col_idx+1] -\ self->g_R_col_idx_H2[this_ws->R_col_idx]; this_ws->flag_reduce = 1; //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nreducing with complex"); //} } } } //printf("\nidx is %d, pivot key2 %d: in red at col idx %d, in R at %d to %d"\ // , idx\ // , self->g_H2_pivots[this_ws->pivot.key1][idx].key2\ // , self->g_H2_pivots[this_ws->pivot.key1][idx].col_idx\ // , self->g_R_col_idx_H2[self->g_H2_pivots[this_ws->pivot.key1][idx].col_idx]\ // , self->g_R_col_idx_H2[self->g_H2_pivots[this_ws->pivot.key1][idx].col_idx+1]\ // ); //} } //if ((this_ws->tetrahedron.key1 == 368174)\ // &&(this_ws->tetrahedron.key2 == 333271)){ // printf("\nQuitting parallel"); //} } pthread_mutex_lock(&(self->g_thread_lock)); self->g_processed_threads++; } } void update_R_H2 (filtration* self, int ws_counter){ boundary_H2_ws* this_ws = self->g_workspace_H2_info + ws_counter; simplex* orig = self->g_workspace_H2[ws_counter] \ + this_ws->original*this_ws->max_len; // Update R if ((self->g_R_len_H2 + this_ws->len) > self->g_R_max_len_H2){ self->g_R_max_len_H2 += 1000 + this_ws->len; self->g_R_H2 = (simplex*)realloc(self->g_R_H2, self->g_R_max_len_H2*sizeof(simplex)); } // Update R col idx self->g_R_col_idx_H2_ptr++; if (self->g_R_col_idx_H2_ptr == self->g_R_col_idx_max_len_H2 - 1){ self->g_R_col_idx_max_len_H2 += 1000; self->g_R_col_idx_H2 = (EDGE_ID*)realloc(self->g_R_col_idx_H2\ , self->g_R_col_idx_max_len_H2*sizeof(EDGE_ID)); } self->g_R_col_idx_H2[self->g_R_col_idx_H2_ptr] = self->g_R_len_H2; //printf("\nAdding pivot %d at %d", this_ws->pivot, self->g_R_col_idx_H2_ptr); // //////////////////// // ADD PIVOT // //////////////////// add_H2_pivot(self, this_ws->tetrahedron, this_ws->pivot, self->g_R_col_idx_H2_ptr); //printf("\nAdding to R with pivot (%d, %d): "\ // , this_ws->pivot.key1\ // , this_ws->pivot.key2\ // ); ////////////////////// for (EDGE_ID mm = 0; mm < this_ws->len; mm++){ self->g_R_H2[self->g_R_len_H2++] = orig[mm]; //printf("(%d, %d), ", self->g_R_H2[self->g_R_len_H2 - 1].key1\ // , self->g_R_H2[self->g_R_len_H2 - 1].key2); } self->g_R_col_idx_H2[self->g_R_col_idx_H2_ptr+1] = self->g_R_len_H2; //if (this_ws->pivot.key1 == 24782){ //printf("\nR_col_idx at %d, in R from from %d to %d"\ // , self->g_R_col_idx_H2_ptr\ // , self->g_R_col_idx_H2[self->g_R_col_idx_H2_ptr]\ // , self->g_R_col_idx_H2[self->g_R_col_idx_H2_ptr+1]); //getchar(); //} //if (this_ws->pivot.key1 == 7173){ // printf("\nThe R is from %d to %d"\ // , self->g_R_col_idx_H2[self->g_R_col_idx_H2_ptr]\ // , self->g_R_col_idx_H2[self->g_R_col_idx_H2_ptr+1]\ // ); // getchar(); //} //PAR birth = self->g_edge_parameter[this_ws->pivot.key1]; //PAR death = self->g_edge_parameter[this_ws->tetrahedron.key1]; //#ifdef BIRTH_HOM_CYCLES // self->g_H1_pivot_of[this_ws->pivot].key1 = this_ws->triangle.key1; // self->g_H1_pivot_of[this_ws->pivot].key2 = this_ws->triangle.key2; //#endif //printf("\n%lf, %lf", birth, death); } void add_H2_pivot (filtration* self, simplex tetrahedron, simplex pivot, EDGE_ID red_col){ if (self->g_H2_pivots_len[pivot.key1]\ == self->g_H2_pivots_max_len[pivot.key1]){ self->g_H2_pivots_max_len[pivot.key1] += 5; self->g_H2_pivots[pivot.key1] = (H2_pivots*)realloc( \ self->g_H2_pivots[pivot.key1] \ , self->g_H2_pivots_max_len[pivot.key1]*sizeof(H2_pivots)); } EDGE_ID old_ptr = self->g_H2_pivots_len[pivot.key1]; EDGE_ID new_ptr = self->g_H2_pivots_len[pivot.key1]; while (old_ptr){ old_ptr--; if (self->g_H2_pivots[pivot.key1][old_ptr].key2 > pivot.key2){ self->g_H2_pivots[pivot.key1][new_ptr--] =\ self->g_H2_pivots[pivot.key1][old_ptr]; continue; } break; } self->g_H2_pivots[pivot.key1][new_ptr].key2 = pivot.key2; self->g_H2_pivots[pivot.key1][new_ptr].col_idx = red_col; self->g_H2_pivots[pivot.key1][new_ptr].tetrahedron = tetrahedron; self->g_H2_pivots_len[pivot.key1]++; //if (pivot.key1 == 7173){ // printf("\nAdding (%d, %d) at R col idx %d"\ // , pivot.key1\ // , pivot.key2\ // , self->g_H2_pivots[pivot.key1][new_ptr].col_idx\ // ); // getchar(); //} // PERS PAIRS // Add non-zero barcodes PAR birth = self->g_edge_parameter[pivot.key1]; PAR death = self->g_edge_parameter[tetrahedron.key1]; if (birth != death){ //printf("\nNon trivial pers pair (%f, %f)", birth, death); //if (birth > death){ // printf("\nBirth, death (%lf, %lf)", birth, death); // printf("\nError (%d, %d) at pair (%d, %d)", triangle.key1\ // , triangle.key2\ // , pivot.key1\ // , pivot.key2); // getchar(); // //} self->g_homH2_pers[self->g_homH2_pers_len].birth_simplex = pivot; self->g_homH2_pers[self->g_homH2_pers_len].death_edge = tetrahedron.key1; self->g_homH2_pers[self->g_homH2_pers_len++].R_col_idx = red_col; //printf("\nAdding (%d, %d) at %d in homH2pers for tetra (%d, %d)"\ // , pivot.key1\ // , pivot.key2\ // , self->g_homH2_pers_len-1\ // , tetrahedron.key1\ // , tetrahedron.key2\ // ); if (self->g_homH2_pers_len == self->g_homH2_pers_max_len){ self->g_homH2_pers_max_len += 100; self->g_homH2_pers = (homH2_pers*)realloc(self->g_homH2_pers\ , self->g_homH2_pers_max_len*sizeof(homH2_pers)); } } } EDGE_ID search_H2_pivots(H2_pivots* arr, EDGE_ID l, EDGE_ID r, EDGE_ID key2, EDGE_ID max) { if (r >= l) { EDGE_ID mid = l + (r - l) / 2; if (arr[mid].key2 == key2) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid].key2 > key2) { /// PRECAUTIONARY: CAN REMOVE LATER if (!mid){ return max; //printf("\nMID 0 WILL GIVE ERROR FOR UNSIGNED NEXT"); //getchar(); } /////////////////// return search_H2_pivots(arr, l, mid - 1, key2, max); } // Else the element can only be present // in right subarray return search_H2_pivots(arr, mid + 1, r, key2, max); } // We reach here when element is not // present in array //printf("\nNOT FOUND"); return max; } void get_birth_void(filtration* self, simplex bo_idx){ self->g_temp_V_H2_primary.len = 1; self->g_temp_V_H2_primary.VV[0] = bo_idx; // Initiate R with the boundary of bo_idx compute_boundary_triangle(self, bo_idx, self->g_temp_R_H2_birth_cycles.RR); //printf("\nComputed cob at line 11582"); //getchar(); self->g_temp_R_H2_birth_cycles.original = 0; self->g_temp_R_H2_birth_cycles.len = 3; EDGE_ID* original_result; EDGE_ID* scratch_result; EDGE_ID j, k, count, possible_len, ro, red_simp_len; EDGE_ID* red_start; EDGE_ID* trivial_boundary = (EDGE_ID*)malloc(3*sizeof(EDGE_ID)); EDGE_ID bo_pivot; #ifdef ADAPTIVE_V_STORAGE self->g_store_V_for_len = 0; #endif self->g_depth = 0; while (self->g_temp_R_H2_birth_cycles.len){ //printf("\nV len is %d", self->g_temp_V_H2_primary.len); original_result = self->g_temp_R_H2_birth_cycles.RR \ + (self->g_temp_R_H2_birth_cycles.original)*self->g_temp_R_H2_birth_cycles.max_len; bo_pivot = original_result[self->g_temp_R_H2_birth_cycles.len-1]; // Check if the pivot-edge is in a trivial pers pair if (self->g_coH1_all_lows[bo_pivot].low.key1 == bo_pivot){ bo_idx = self->g_coH1_all_lows[bo_pivot].low; // Get the boundary of R compute_boundary_triangle(self, bo_idx, trivial_boundary); red_simp_len = 3; red_start = trivial_boundary; // The V-operation for this is exactly bo_idx self->g_temp_V_H2_primary.VV[self->g_temp_V_H2_primary.len++] = bo_idx; // Check for overflow if (self->g_temp_V_H2_primary.len == self->g_temp_V_H2_primary.max_len){ //getchar(); self->g_temp_V_H2_primary.max_len += 100; //printf("\nReallocating %d", self->g_temp_V_H2_primary.max_len); self->g_temp_V_H2_primary.VV = (simplex*)realloc(self->g_temp_V_H2_primary.VV\ , self->g_temp_V_H2_primary.max_len*sizeof(simplex)); } } else{ bo_idx = self->g_H1_pivot_of[bo_pivot].coface; ro = self->g_pivots_H1[bo_pivot]; red_simp_len = self->g_R_col_idx_H1[ro+1] - \ self->g_R_col_idx_H1[ro]; red_start = self->g_R_H1 + self->g_R_col_idx_H1[ro]; // For this one we have to find V recursively // FIND THE V RECURSIVELY find_V_recursively_triangles(self, bo_idx, bo_pivot); } // Check for overflow of R_H2 possible_len = self->g_temp_R_H2_birth_cycles.len + red_simp_len; if (possible_len > self->g_temp_R_H2_birth_cycles.max_len - 1){ if (self->g_temp_R_H2_birth_cycles.original){ for (EDGE_ID k = 0; k < self->g_temp_R_H2_birth_cycles.len; k++){ self->g_temp_R_H2_birth_cycles.RR[k] =\ self->g_temp_R_H2_birth_cycles.RR[k + self->g_temp_R_H2_birth_cycles.max_len]; } } self->g_temp_R_H2_birth_cycles.max_len = possible_len + 1000; self->g_temp_R_H2_birth_cycles.RR = (EDGE_ID*)realloc(self->g_temp_R_H2_birth_cycles.RR\ , (2*self->g_temp_R_H2_birth_cycles.max_len)*sizeof(EDGE_ID)); original_result = self->g_temp_R_H2_birth_cycles.RR; self->g_temp_R_H2_birth_cycles.original = 0; } scratch_result = self->g_temp_R_H2_birth_cycles.RR \ + (1-self->g_temp_R_H2_birth_cycles.original)*self->g_temp_R_H2_birth_cycles.max_len; // Reduce j = 0; k = 0; count = 0; while ((j < self->g_temp_R_H2_birth_cycles.len) && (k < red_simp_len)){ if (original_result[j] < red_start[k]){ scratch_result[count] = original_result[j]; count = count + 1; j = j + 1; } else if (original_result[j] > red_start[k]){ scratch_result[count] = red_start[k]; count = count + 1; k = k + 1; } else{ j = j + 1; k = k + 1; } } while (j < self->g_temp_R_H2_birth_cycles.len){ scratch_result[count++] = original_result[j++]; } while (k < red_simp_len){ scratch_result[count++] = red_start[k++]; } self->g_temp_R_H2_birth_cycles.len = count; self->g_temp_R_H2_birth_cycles.original = 1 - self->g_temp_R_H2_birth_cycles.original; } //printf("\nreducing temp V at line 11735"); //getchar(); reduce_temp_V_H1(self); //printf("\nreduced V at line 11735. Press key to continue"); //getchar(); free(trivial_boundary); } void find_V_recursively_triangles(filtration* self, simplex bo_idx, EDGE_ID bo_pivot){ #ifdef RECORD_V_USAGE self->g_H1_pivot_of[bo_pivot].V_usage++; #endif #ifdef ADAPTIVE_V_STORAGE if (self->g_H1_pivot_of[bo_pivot].V_stored == 1){ //printf("\nUsing stored cycle for %d of length %d, temp_V_H2 length is %d, max %d"\ // , bo_idx\ // , self->g_H1_pivot_of[bo_pivot].V_len\ // , self->g_temp_V_H2_primary.len\ // , self->g_temp_V_H2_primary.max_len\ // ); if ((self->g_temp_V_H2_primary.len + self->g_H1_pivot_of[bo_pivot].V_len) > self->g_temp_V_H2_primary.max_len - 1){ self->g_temp_V_H2_primary.max_len =\ self->g_temp_V_H2_primary.len + self->g_H1_pivot_of[bo_pivot].V_len + 1000; //printf("\nReallocating %d", self->g_temp_V_H2_primary.max_len); self->g_temp_V_H2_primary.VV = (simplex*)realloc(self->g_temp_V_H2_primary.VV\ , self->g_temp_V_H2_primary.max_len*sizeof(simplex)); } for (EDGE_ID mm = 0; mm < self->g_H1_pivot_of[bo_pivot].V_len; mm++){ self->g_temp_V_H2_primary.VV[self->g_temp_V_H2_primary.len++] =\ self->g_H1_pivot_of[bo_pivot].VV[mm]; } return; } else if (self->g_H1_pivot_of[bo_pivot].V_stored != -1){ #ifndef RECORD_V_USAGE self->g_H1_pivot_of[bo_pivot].V_usage++; #endif if ((self->g_H1_pivot_of[bo_pivot].V_usage > self->g_cycle_usage_thresh)\ &&(!self->g_H1_pivot_of[bo_pivot].V_stored)){ //printf("\nstore simplex (%d, %d) that has pivot %d", bo_idx.key1\ // , bo_idx.key2\ // , bo_pivot); self->g_store_V_for[self->g_store_V_for_len++] = bo_pivot; if (self->g_store_V_for_len == self->g_store_V_for_max_len){ self->g_store_V_for_max_len += 100; self->g_store_V_for = (EDGE_ID*)realloc(self->g_store_V_for\ , self->g_store_V_for_max_len*sizeof(EDGE_ID)); } } } #endif //printf("\nComputing V for %d, temp_V_H2 length is %d, max %d" , bo_idx\ // , self->g_temp_V_H2_primary.len\ // , self->g_temp_V_H2_primary.max_len\ ); EDGE_ID res_max_len = 100; EDGE_ID* result = (EDGE_ID*)malloc((2*res_max_len)*sizeof(EDGE_ID)); int res_original = 0; EDGE_ID* original_result; EDGE_ID* scratch_result; //printf("\nstarting red for depth %d", self->g_depth); // Initiate R with the boundary of bo_idx compute_boundary_triangle(self, bo_idx, result); EDGE_ID res_len = 3; EDGE_ID possible_len; EDGE_ID* red_start; EDGE_ID red_simp_len; EDGE_ID ro; EDGE_ID j, k, count; EDGE_ID* trivial_boundary = (EDGE_ID*)malloc(3*sizeof(EDGE_ID)); self->g_temp_V_H2_primary.VV[self->g_temp_V_H2_primary.len++] = bo_idx; // Check for overflow if (self->g_temp_V_H2_primary.len == self->g_temp_V_H2_primary.max_len){ //printf("\nReallocating"); //getchar(); self->g_temp_V_H2_primary.max_len += 100; //printf("\nReallocating %d", self->g_temp_V_H2_primary.max_len); self->g_temp_V_H2_primary.VV = (simplex*)realloc(self->g_temp_V_H2_primary.VV\ , self->g_temp_V_H2_primary.max_len*sizeof(simplex)); } //int flag_recursive = 0; while(res_len != 0){ #ifdef ADAPTIVE_V_STORAGE self->g_depth++; #endif original_result = result + (res_original*res_max_len); bo_pivot = original_result[res_len-1]; // Check for trivial pers pair if (self->g_coH1_all_lows[bo_pivot].low.key1 == bo_pivot){ //printf("\nreducing with trivial"); bo_idx = self->g_coH1_all_lows[bo_pivot].low; // Get the boundary of R compute_boundary_triangle(self, bo_idx, trivial_boundary); red_simp_len = 3; red_start = trivial_boundary; } else{ //printf("\nreducing with complex"); bo_idx = self->g_H1_pivot_of[bo_pivot].coface; ro = self->g_pivots_H1[bo_pivot]; //printf("\n r_col_idx is %d", ro); red_simp_len = self->g_R_col_idx_H1[ro+1] - \ self->g_R_col_idx_H1[ro]; red_start = self->g_R_H1 + self->g_R_col_idx_H1[ro]; } // Check for overflow possible_len = res_len + red_simp_len; if (possible_len > res_max_len - 1){ if (res_original){ for (k = 0; k < res_len; k++){ result[k] = result[k + res_max_len]; } } res_max_len = possible_len + 1000; result = (EDGE_ID*)realloc(result, (2*res_max_len)*sizeof(EDGE_ID)); original_result = result; res_original = 0; } scratch_result = result + ((1-res_original)*res_max_len); //printf("\nReducing "); //for (EDGE_ID mm = 0; mm < res_len; mm++){ // printf("%d, ", original_result[mm]); //} //printf("\nwith "); //for (EDGE_ID mm = 0; mm < red_simp_len; mm++){ // printf("%d, ", red_start[mm]); //} // Reduce j = 0; k = 0; count = 0; while ((j < res_len) && (k < red_simp_len)){ if (original_result[j] < red_start[k]){ scratch_result[count] = original_result[j]; count = count + 1; j = j + 1; } else if (original_result[j] > red_start[k]){ scratch_result[count] = red_start[k]; count = count + 1; k = k + 1; } else{ j = j + 1; k = k + 1; } } while (j < res_len){ scratch_result[count++] = original_result[j++]; } while (k < red_simp_len){ scratch_result[count++] = red_start[k++]; } res_len = count; res_original = 1 - res_original; if (res_len != 0){ find_V_recursively_triangles(self, bo_idx, bo_pivot); } } free(result); free(trivial_boundary); } void compute_boundary_tetra(filtration* self, simplex tetra, simplex* simp){ EDGE_ID o_ab = tetra.key1; VERT_ID a = self->g_edges_list[2*o_ab]; VERT_ID b = self->g_edges_list[2*o_ab+1]; EDGE_ID o_cd = tetra.key2; VERT_ID c = self->g_edges_list[2*o_cd]; VERT_ID d = self->g_edges_list[2*o_cd+1]; // Since d > c, abd is the maximum triangle simp[3].key1 = o_ab; simp[3].key2 = d; // abc simp[2].key1 = o_ab; simp[2].key2 = c; // Remaining triangles are bcd and acd // Get all edges first VERT_ID idx = search_Neighbors(self, b, d, 0, self->g_Neigh_len[b]-1); EDGE_ID o_bd = self->g_Neighbors[b][idx].order; idx = search_Neighbors(self, a, d, 0, self->g_Neigh_len[a]-1); EDGE_ID o_ad = self->g_Neighbors[a][idx].order; idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); EDGE_ID o_ac = self->g_Neighbors[a][idx].order; idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); EDGE_ID o_bc = self->g_Neighbors[b][idx].order; // Triangle bcd EDGE_ID o_max = o_bc; VERT_ID v3 = d; if (o_cd > o_max){ o_max = o_cd; v3 = b; } if (o_bd > o_max){ o_max = o_bd; v3 = c; } // Triangle acd EDGE_ID o_max_2 = o_ac; VERT_ID v3_2 = d; if (o_cd > o_max_2){ o_max_2 = o_cd; v3_2 = a; } if (o_ad > o_max_2){ o_max_2 = o_ad; v3_2 = c; } int compare = -1; if (o_max > o_max_2) compare = 1; else if (o_max < o_max_2) compare = 0; else{ if (v3 > v3_2) compare = 1; else if (v3 < v3_2) compare = 0; else compare = -1; } if (compare == 1){ simp[1].key1 = o_max; simp[1].key2 = v3; simp[0].key1 = o_max_2; simp[0].key2 = v3_2; } else if (compare == 0){ simp[1].key1 = o_max_2; simp[1].key2 = v3_2; simp[0].key1 = o_max; simp[0].key2 = v3; } else{ printf("\nERROR? 10119"); getchar(); } } void compute_boundary_triangle(filtration* self, simplex triangle, EDGE_ID* simp){ VERT_ID a = self->g_edges_list[2*triangle.key1]; VERT_ID b = self->g_edges_list[2*triangle.key1+1]; VERT_ID c = triangle.key2; VERT_ID idx = search_Neighbors(self, a, c, 0, self->g_Neigh_len[a]-1); EDGE_ID o_ac = self->g_Neighbors[a][idx].order; idx = search_Neighbors(self, b, c, 0, self->g_Neigh_len[b]-1); EDGE_ID o_bc = self->g_Neighbors[b][idx].order; if (o_ac > o_bc){ simp[0] = o_bc; simp[1] = o_ac; } else{ simp[0] = o_ac; simp[1] = o_bc; } simp[2] = triangle.key1; //printf("\nComputed boundary of triangle (%d, %d, %d)"\ // , simp[0]\ // , simp[1]\ // , simp[2]\ // ); } void store_V_H0(filtration* self){ for (EDGE_ID nn = 0; nn < self->g_store_V_for_len; nn++){ EDGE_ID bo_pivot = self->g_store_V_for[nn]; if (self->g_H0_pivot_of[bo_pivot].V_len){ continue; } //printf("\nstoring %d", bo_pivot); self->g_temp_V_primary.len = 0; EDGE_ID bo_idx = self->g_H0_pivot_of[bo_pivot].coface; self->g_depth = 0; find_V_recursively_edges(self, bo_idx, bo_pivot); #ifdef RECORD_V_USAGE self->g_H0_pivot_of[bo_pivot].V_depth = self->g_depth; #endif if (self->g_depth < self->g_cycle_depth_thresh){ self->g_H0_pivot_of[bo_pivot].V_stored = -1; continue; } self->g_n_H0_stored_V++; //printf("\nstoring %d with depth %d", bo_pivot, self->g_depth); self->g_H0_pivot_of[bo_pivot].V_stored = 1; // Reduce V reduce_temp_V_H0(self); //printf("\nlen is %d", self->g_temp_V_primary.len); self->g_H0_pivot_of[bo_pivot].V_len = self->g_temp_V_primary.len; self->g_H0_pivot_of[bo_pivot].VV = \ (EDGE_ID*)malloc(self->g_temp_V_primary.len*sizeof(EDGE_ID)); for (EDGE_ID oo = 0; oo < self->g_temp_V_primary.len; oo++){ self->g_H0_pivot_of[bo_pivot].VV[oo] = self->g_temp_V_primary.VV[oo]; } } } void reduce_temp_V_H0(filtration* self){ //// Reduce V sorter8_tim_sort(self->g_temp_V_primary.VV, self->g_temp_V_primary.len); int coeff = 1; EDGE_ID idx = 0; for (EDGE_ID vv = 0; vv < self->g_temp_V_primary.len-1; vv++){ if (self->g_temp_V_primary.VV[vv] == self->g_temp_V_primary.VV[vv+1]) { coeff = 1 - coeff; } else{ if (coeff){ //self->g_V_sparse_H1[self->g_V_sparse_ptr++] = this_ws->v_edges.o_ab[vv]; self->g_temp_V_primary.VV[idx++] = self->g_temp_V_primary.VV[vv]; } coeff = 1; } } if (coeff){ self->g_temp_V_primary.VV[idx++] = self->g_temp_V_primary.VV[self->g_temp_V_primary.len-1]; } self->g_temp_V_primary.len = idx; } void store_V_H1(filtration* self){ for (EDGE_ID nn = 0; nn < self->g_store_V_for_len; nn++){ EDGE_ID bo_pivot = self->g_store_V_for[nn]; //printf("\nPress key to store V for pivot %d", bo_pivot); //getchar(); if (self->g_H1_pivot_of[bo_pivot].V_len){ continue; } // Check for trivial pers pair if (self->g_coH1_all_lows[bo_pivot].low.key1 == bo_pivot){ self->g_H1_pivot_of[bo_pivot].V_stored = -1; //printf("\nNot storing because trivial, %d", bo_pivot); //getchar(); continue; } self->g_n_H1_stored_V++; //printf("\nchecking depth for pivot %d", bo_pivot); //getchar(); self->g_temp_V_H2_primary.len = 0; simplex bo_idx = self->g_H1_pivot_of[bo_pivot].coface; //printf(", simplex is (%d, %d)", bo_idx.key1, bo_idx.key2); //getchar(); self->g_depth = 0; find_V_recursively_triangles(self, bo_idx, bo_pivot); #ifdef RECORD_V_USAGE self->g_H1_pivot_of[bo_pivot].V_depth = self->g_depth; #endif if (self->g_depth < self->g_cycle_depth_thresh){ self->g_H1_pivot_of[bo_pivot].V_stored = -1; continue; } //printf("\nstoring %d with depth %d", bo_pivot, self->g_depth); self->g_H1_pivot_of[bo_pivot].V_stored = 1; //self->g_H1_pivot_of[bo_pivot].V_depth = self->g_depth; // Reduce V reduce_temp_V_H1(self); self->g_H1_pivot_of[bo_pivot].V_len = self->g_temp_V_H2_primary.len; self->g_H1_pivot_of[bo_pivot].VV = \ (simplex*)malloc(self->g_temp_V_H2_primary.len*sizeof(simplex)); for (EDGE_ID oo = 0; oo < self->g_temp_V_H2_primary.len; oo++){ self->g_H1_pivot_of[bo_pivot].VV[oo] = self->g_temp_V_H2_primary.VV[oo]; } } } void reduce_temp_V_H1(filtration* self){ //// Reduce V sorter4_tim_sort(self->g_temp_V_H2_primary.VV, self->g_temp_V_H2_primary.len); int coeff = 1; EDGE_ID idx = 0; for (EDGE_ID vv = 0; vv < self->g_temp_V_H2_primary.len-1; vv++){ if ((self->g_temp_V_H2_primary.VV[vv].key1 == self->g_temp_V_H2_primary.VV[vv+1].key1)\ &&(self->g_temp_V_H2_primary.VV[vv].key2 == self->g_temp_V_H2_primary.VV[vv+1].key2)) { coeff = 1 - coeff; } else{ if (coeff){ //self->g_V_sparse_H1[self->g_V_sparse_ptr++] = this_ws->v_edges.o_ab[vv]; self->g_temp_V_H2_primary.VV[idx++] = self->g_temp_V_H2_primary.VV[vv]; } coeff = 1; } } if (coeff){ self->g_temp_V_H2_primary.VV[idx++] = self->g_temp_V_H2_primary.VV[self->g_temp_V_H2_primary.len-1]; } self->g_temp_V_H2_primary.len = idx; } EDGE_ID bin_search_max_less_V(EDGE_ID* arr, EDGE_ID l, EDGE_ID r, EDGE_ID x, EDGE_ID MAX){ //printf("\nl %d, r %d", l, r); if (arr[r] >= x){ //printf("\nreturing max"); return MAX; } if (arr[l] < x){ //printf("\nreturing l %d", l); return l; } EDGE_ID mid = l + (r-l)/2; //printf("\nmid is %d", mid); if (arr[mid] >= x){ l = mid+1; bin_search_max_less_V(arr, l, r, x, MAX); } else{ r = mid-1; bin_search_max_less_V(arr, l , r, x, MAX); } } EDGE_ID bin_search_max_less_updated_V(min_update_V* arr, EDGE_ID l, EDGE_ID r, EDGE_ID x, EDGE_ID MAX){ //printf("\nl %d, r %d", l, r); if (arr[r].cycid >= x){ //printf("\nreturing max"); return MAX; } if (arr[l].cycid < x){ //printf("\nreturing l %d", l); return l; } EDGE_ID mid = l + (r-l)/2; //printf("\nmid is %d", mid); if (arr[mid].cycid >= x){ l = mid+1; bin_search_max_less_updated_V(arr, l, r, x, MAX); } else{ r = mid-1; bin_search_max_less_updated_V(arr, l , r, x, MAX); } } EDGE_ID bin_search_min_greater_updated_V_byLidx(EDGE_ID* arr, EDGE_ID l, EDGE_ID r, EDGE_ID x, EDGE_ID MAX){ //printf("\nl %d, r %d", l, r); if (arr[r] <= x){ //printf("\nreturing max"); return MAX; } if (arr[l] > x){ //printf("\nreturing l %d", l); return l; } EDGE_ID mid = l + (r-l)/2; //printf("\nmid is %d", mid); if (arr[mid] <= x){ l = mid+1; bin_search_min_greater_updated_V_byLidx(arr, l, r, x, MAX); } else{ r = mid; if (arr[r-1] <= x) return r; bin_search_min_greater_updated_V_byLidx(arr, l , r, x, MAX); } } void minimize_birth_cycles_H0_v2(filtration* self\ , EDGE_ID** stored_boundaries\ , EDGE_ID* len_boundaries\ , EDGE_ID stored_num\ , char* filename\ ){ EDGE_ID** all_diff = (EDGE_ID**)malloc(self->g_all_V_stored_num*sizeof(EDGE_ID*)); for (EDGE_ID mm = 0; mm < self->g_all_V_stored_num; mm++){ all_diff[mm] = (EDGE_ID*)malloc(2*sizeof(EDGE_ID)); } EDGE_ID* updated = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); EDGE_ID* original_id = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); for (EDGE_ID mm = 0; mm < stored_num; mm++){ original_id[mm] = mm; } mergeSort_V_H0(len_boundaries, stored_boundaries, updated, original_id \ , 0, stored_num-1); //printf("\nInitial sums"); //omp_set_num_threads(2*self->g_cpu_count-1); #pragma omp parallel for schedule(guided) shared(self, stored_boundaries, len_boundaries, stored_num, all_diff) for (EDGE_ID mm = 0; mm < stored_num; mm++){ if (!self->g_suppress_output){ if (mm%1000 == 0) printf("\nDoing %d", mm); } all_diff[mm][0] = 0; all_diff[mm][1] = 0; for (EDGE_ID nn = mm+1; nn < stored_num; nn++){ if (len_boundaries[nn] < all_diff[mm][1]){ break; } EDGE_ID j, k, count; j = 0; k = 0; count = 0; int quit_flag = 0; while ((j < len_boundaries[mm]) && (k < len_boundaries[nn])){ if (stored_boundaries[mm][j] < stored_boundaries[nn][k]){ count++; j++; } else if (stored_boundaries[mm][j] > stored_boundaries[nn][k]){ count++; k++; } else{ j++; k++; } if (count > len_boundaries[mm] - all_diff[mm][1]){ quit_flag = 1; break; } } if (quit_flag) continue; if (j < len_boundaries[mm]){ count += len_boundaries[mm] - j; } if (count > len_boundaries[mm] - all_diff[mm][1]){ continue; } if (k < len_boundaries[nn]){ count += len_boundaries[nn] - k; } if (count > len_boundaries[mm] - all_diff[mm][1]){ continue; } if (count < len_boundaries[mm]){ if ((len_boundaries[mm] - count) > all_diff[mm][1]){ all_diff[mm][0] = nn; all_diff[mm][1] = len_boundaries[mm] - count; } } } } } ////////////////////////////////////////////////////////// // MERGE SORT ALGORITHMS FOR update_V ////////////////////////////////////////////////////////// // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_update_V(min_update_V* arr, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ min_update_V *L, *R; L = (min_update_V*)malloc(n1*sizeof(min_update_V)); R = (min_update_V*)malloc(n2*sizeof(min_update_V)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i].cycid > R[j].cycid) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } free(L); free(R); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_update_V(min_update_V* arr, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_update_V(arr, l, m); mergeSort_update_V(arr, m+1, r); merge_update_V(arr, l, m, r); } } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge_update_V_byLidx(min_update_V* arr, EDGE_ID l, EDGE_ID m, EDGE_ID r) { EDGE_ID i, j, k; EDGE_ID n1 = m - l + 1; EDGE_ID n2 = r - m; //printf("\nn1, n2: %u, %u", n1, n2); /* create temp arrays */ min_update_V *L, *R; L = (min_update_V*)malloc(n1*sizeof(min_update_V)); R = (min_update_V*)malloc(n2*sizeof(min_update_V)); //int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++){ L[i] = arr[l + i]; } for (j = 0; j < n2; j++) { R[j] = arr[m + 1+ j]; } /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i].Lidx < R[j].Lidx) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } free(L); free(R); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort_update_V_byLidx(min_update_V* arr, EDGE_ID l, EDGE_ID r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h EDGE_ID m = l+(r-l)/2; // Sort first and second halves mergeSort_update_V_byLidx(arr, l, m); mergeSort_update_V_byLidx(arr, m+1, r); merge_update_V_byLidx(arr, l, m, r); } } EDGE_ID find_first_diff_H0(EDGE_ID* len_boundaries\ , EDGE_ID stored_num\ , EDGE_ID** stored_boundaries){ EDGE_ID difff = 0; for (EDGE_ID mm = 0; mm < stored_num; mm++){ if (len_boundaries[mm] < difff){ break; } for (EDGE_ID nn = mm+1; nn < stored_num; nn++){ if (len_boundaries[nn] < difff){ break; } EDGE_ID j, k, count; j = 0; k = 0; count = 0; int quit_flag = 0; while ((j < len_boundaries[mm]) && (k < len_boundaries[nn])){ if (stored_boundaries[mm][j] < stored_boundaries[nn][k]){ count++; j++; } else if (stored_boundaries[mm][j] > stored_boundaries[nn][k]){ count++; k++; } else{ j++; k++; } if (count > len_boundaries[mm] - difff){ quit_flag = 1; break; } } if (quit_flag) continue; if (j < len_boundaries[mm]){ count += len_boundaries[mm] - j; } if (count > len_boundaries[mm] - difff){ continue; } if (k < len_boundaries[nn]){ count += len_boundaries[nn] - k; } if (count > len_boundaries[mm] - difff){ continue; } //printf("\n%d, %d, %d",len_boundaries[mm], count, difff); if (count < len_boundaries[mm]){ if ((len_boundaries[mm] - count) > difff){ difff = len_boundaries[mm] - count; } } } } return difff; } void minimize_birth_cycles_H0_v3(filtration* self\ , cyc_info* CC\ , EDGE_ID stored_num\ , char* filename\ , char* lens_filename\ , char* minimal_lens_filename\ , char* subset_points_file\ ){ //, char* filename2\ if (!self->g_suppress_output){ printf("\nNumber of cycles %d", stored_num); } //getchar(); #ifdef STORE_LENGTHS_CYCLES FILE* fp0 = fopen(lens_filename, "w"); for (EDGE_ID ci = 0; ci < stored_num; ci++){ fprintf(fp0, "%d, ", CC[ci].len); if (!self->g_reduce_cyc_lengths){ free(CC[ci].boundary); } } if (!self->g_reduce_cyc_lengths){ free(CC); } fclose(fp0); #endif if (!self->g_reduce_cyc_lengths){ return; } omp_set_num_threads(2*self->g_cpu_count - 1); EDGE_ID* Lcycid = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID* Llen = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID* Lupdated = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); update_in_cyc** update_in_cycle = (update_in_cyc**)malloc(self->g_n_valid_edges*sizeof(update_in_cyc*)); EDGE_ID* update_in_cycle_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); EDGE_ID* update_in_cycle_max_len = (EDGE_ID*)calloc(self->g_n_valid_edges, sizeof(EDGE_ID)); for (EDGE_ID bb = 0; bb < self->g_n_valid_edges; bb++){ update_in_cycle_max_len[bb] = 1; update_in_cycle[bb] = (update_in_cyc*)malloc(sizeof(update_in_cyc)); } EDGE_ID* update_edges = (EDGE_ID*)malloc(self->g_n_valid_edges*sizeof(EDGE_ID)); EDGE_ID update_edges_num = 0; EDGE_ID* case2a2bb = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID case2a2bb_num = 0; EDGE_ID* case2ba = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID case2ba_num = 0; //printf("\nIntializing L, C.Lidx..."); // Step 1. Initialize L and C.Lidx for (EDGE_ID i = 0; i < stored_num; i++){ Lcycid[i] = i; Llen[i] = CC[i].len; Lupdated[i] = 0; } //printf("\nSorting Llen..."); // Step 2(a): Sort Llen, Lcycid, Lupdated by Llen mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); //printf("\nInitializing C.Lidx..."); // Step 2(b): Initialize C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } //// Cycle-intersects-cycle information //cyc_in_cyc** cyc_inter_cyc = (cyc_in_cyc**)malloc(stored_num*sizeof(cyc_in_cyc*)); //EDGE_ID* cyc_inter_cyc_len = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); //EDGE_ID* cyc_inter_cyc_max_len = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); // BUILD VERT to cycle association for (EDGE_ID ci = 0; ci < stored_num; ci++){ EDGE_ID li = CC[ci].Lidx; for (EDGE_ID idx = 0; idx < CC[ci].len; idx++){ EDGE_ID edge = CC[ci].boundary[idx]; //printf("\nedge is %d with %d cycles ", edge, self->g_edges_in_cycles_len[edge]); //for (EDGE_ID nn = 0; nn < self->g_edges_in_cycles_len[edge]; nn++){ // printf("%d, ", self->g_edges_in_cycles[edge][nn]); //} if (!self->g_edges_in_cycles_len[edge]){ self->g_edges_in_cycles[edge] = (EDGE_ID*)malloc(sizeof(EDGE_ID)); } else{ self->g_edges_in_cycles[edge] = (EDGE_ID*)realloc(\ self->g_edges_in_cycles[edge]\ ,(self->g_edges_in_cycles_len[edge]+1)*sizeof(EDGE_ID)); } self->g_edges_in_cycles[edge][self->g_edges_in_cycles_len[edge]++] = ci; } } // NOTE: At this point g_edges_in_cycles is sorted by cyc_id if (!self->g_suppress_output){ printf("\nInitializing diff..."); } #pragma omp parallel for schedule(static, 1000) shared(Lcycid, CC, Llen) for (EDGE_ID li = 0; li < stored_num; li++){ EDGE_ID ci = Lcycid[li]; CC[ci].diff = 0; if (!self->g_suppress_output){ if (li %1000 == 0){ printf("\n%d", li); } } for (EDGE_ID lj = li + 1; lj < stored_num; lj++){ //for (EDGE_ID lj = 0; lj < stored_num; lj++){ if (Llen[lj] < CC[ci].diff){ break; } //if (Llen[lj] > Llen[li]){ // continue; //} EDGE_ID cj = Lcycid[lj]; //if (CC[cj].perspair[0] > CC[ci].perspair[0]){ // continue; //} //if (CC[cj].updated_birth > self->g_cycle_min_birth_thresh){ // continue; //} EDGE_ID j, k, count; j = 0; k = 0; count = 0; int quit_flag = 0; while ((j < Llen[li]) && (k < Llen[lj])){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ j++; count++; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ k++; count++; } else{ j++; k++; } if (count >= Llen[li]){ quit_flag = 1; break; } if ((Llen[li] - CC[ci].diff) <= count){ quit_flag = 1; break; } } if (quit_flag){ continue; } if (j < Llen[li]){ count += Llen[li] - j; } if (k < Llen[lj]){ count += Llen[lj] - k; } if (count >= Llen[li]){ continue; } if ((Llen[li] - CC[ci].diff) <= count){ continue; } // At this point len - count < diff? CC[ci].diff = Llen[li] - count; CC[ci].redw = cj; } } //for (EDGE_ID ci = 0; ci < stored_num; ci++){ // if (CC[ci].diff) // printf("\nmax diff for %d is %d", ci, CC[ci].diff); //} //getchar(); // Define V that will store summations to be done EDGE_ID V_len = 0; EDGE_ID V_max_len = 10; min_update_V* update_V = (min_update_V*)malloc(V_max_len*sizeof(min_update_V)); EDGE_ID* update_v_indices = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); int* update_edges_flag = (int*)calloc(self->g_n_valid_edges, sizeof(int)); update_edges_num = 0; EDGE_ID it_counter = 0; // Step 4: Loop for minimization while (1){ struct timespec ss0, ss1, ss2, ss3, ss4, ss5, ss6; struct timespec ff0, ff1, ff2, ff3, ff4, ff5, ff6; double cc0 = 0; double cc1 = 0; double cc2 = 0; double cc3 = 0; double cc4 = 0; double cc5 = 0; double cc6 = 0; if (!self->g_suppress_output){ printf("\n\nIteration %d", it_counter++); clock_gettime(CLOCK_MONOTONIC, &ss0); clock_gettime(CLOCK_MONOTONIC, &ss1); } //printf("\nFINDING MAX DIFF"); // Step 4(a): Find max diff EDGE_ID dm = 1; V_len = 0; for (EDGE_ID ci = 0; ci < stored_num; ci++){ if (CC[ci].diff > dm){ dm = CC[ci].diff; update_V[0].cycid = ci; V_len = 1; } else if (CC[ci].diff == dm){ update_V[V_len++].cycid = ci; if (V_len == V_max_len){ V_max_len += 100; update_V = (min_update_V*)realloc(update_V\ , V_max_len*sizeof(min_update_V)); } } } if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &ff1); cc1 += (ff1.tv_sec - ss1.tv_sec); cc1 += (ff1.tv_nsec - ss1.tv_nsec) / 1000000000.0; } if (!V_len){ //printf("\nDiff 0. EXITING."); break; } //printf("\nMax diff %d in pairs %d", dm, V_len); //printf("\ndo 15453"); //getchar(); if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &ss2); } //#pragma omp parallel for schedule(static, 50) shared(update_V, CC) for (EDGE_ID vi = 0; vi < V_len; vi++){ //if (vi % 1000 == 0){ // printf("\nreducing %d", vi); //} EDGE_ID ci = update_V[vi].cycid; EDGE_ID cj = CC[ci].redw; //printf("\nReducing %d with %d", ci, cj); EDGE_ID* scratch = (EDGE_ID*)malloc((CC[ci].len + CC[cj].len)*sizeof(EDGE_ID)); EDGE_ID edge; EDGE_ID j = 0; EDGE_ID k = 0; EDGE_ID count = 0; while ((j < CC[ci].len) && (k < CC[cj].len)){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ scratch[count++] = CC[ci].boundary[j++]; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ scratch[count] = CC[cj].boundary[k]; // This edge is new in ci // So, add this edge to ci-info edge = CC[cj].boundary[k]; if (!update_edges_flag[edge]){ update_edges_flag[edge] = 1; update_edges[update_edges_num++] = edge; } update_in_cycle[edge][update_in_cycle_len[edge]].cyc = ci; // Add ci in edge update_in_cycle[edge][update_in_cycle_len[edge]].flag = 1; update_in_cycle_len[edge]++; if (update_in_cycle_len[edge] == update_in_cycle_max_len[edge]){ update_in_cycle_max_len[edge] += 100; update_in_cycle[edge] = (update_in_cyc*)realloc(update_in_cycle[edge]\ , update_in_cycle_max_len[edge]*sizeof(update_in_cyc)); } count++; k++; } else{ // This edge is not there anymore in ci // so, remove ci from this edge's info edge = CC[ci].boundary[j]; if (!update_edges_flag[edge]){ update_edges_flag[edge] = 1; update_edges[update_edges_num++] = edge; } update_in_cycle[edge][update_in_cycle_len[edge]].cyc = ci; // Remove ci from edge update_in_cycle[edge][update_in_cycle_len[edge]].flag = 0; update_in_cycle_len[edge]++; if (update_in_cycle_len[edge] == update_in_cycle_max_len[edge]){ update_in_cycle_max_len[edge] += 100; update_in_cycle[edge] = (update_in_cyc*)realloc(update_in_cycle[edge]\ , update_in_cycle_max_len[edge]*sizeof(update_in_cyc)); } j++; k++; } } // update_in_cyc will have unique while (j < CC[ci].len){ // No change scratch[count++] = CC[ci].boundary[j++]; } while (k < CC[cj].len){ // These are all new edges // So, add ci to every edge-info scratch[count] = CC[cj].boundary[k]; edge = CC[cj].boundary[k]; if (!update_edges_flag[edge]){ update_edges_flag[edge] = 1; update_edges[update_edges_num++] = edge; } update_in_cycle[edge][update_in_cycle_len[edge]].cyc = ci; // Add ci in edge update_in_cycle[edge][update_in_cycle_len[edge]].flag = 1; update_in_cycle_len[edge]++; if (update_in_cycle_len[edge] == update_in_cycle_max_len[edge]){ update_in_cycle_max_len[edge] += 100; update_in_cycle[edge] = (update_in_cyc*)realloc(update_in_cycle[edge]\ , update_in_cycle_max_len[edge]*sizeof(update_in_cyc)); } count++; k++; } scratch = (EDGE_ID*)realloc(scratch, count*sizeof(EDGE_ID)); update_V[vi].VV = scratch; update_V[vi].V_len = count; } if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &ff2); cc2 += (ff2.tv_sec - ss2.tv_sec); cc2 += (ff2.tv_nsec - ss2.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &ss6); clock_gettime(CLOCK_MONOTONIC, &ff6); cc6 += (ff6.tv_sec - ss6.tv_sec); cc6 += (ff6.tv_nsec - ss6.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &ss3); printf("\nNumber of edges to update %d", update_edges_num); } #pragma omp parallel for schedule(static, 50) shared(self, stored_num\ , CC\ , Lcycid, Lupdated\ , update_V, V_len\ , update_edges\ , update_in_cycle\ , update_in_cycle_len\ ) for (EDGE_ID iddx = 0; iddx < update_edges_num; iddx++){ EDGE_ID ei = update_edges[iddx]; update_edges_flag[ei] = 0; EDGE_ID* scratch = (EDGE_ID*)malloc(\ (self->g_edges_in_cycles_len[ei]+update_in_cycle_len[ei])*sizeof(EDGE_ID)); EDGE_ID o_ptr = 0; EDGE_ID u_ptr = 0; EDGE_ID s_ptr = 0; while ((o_ptr < self->g_edges_in_cycles_len[ei]) && (u_ptr < update_in_cycle_len[ei])){ if (self->g_edges_in_cycles[ei][o_ptr] < update_in_cycle[ei][u_ptr].cyc){ scratch[s_ptr++] = self->g_edges_in_cycles[ei][o_ptr++]; } else if (self->g_edges_in_cycles[ei][o_ptr] > update_in_cycle[ei][u_ptr].cyc){ // Check if update_in_cycle is flagged for addition if (update_in_cycle[ei][u_ptr].flag){ scratch[s_ptr++] = update_in_cycle[ei][u_ptr++].cyc; } else{ // Sanity check printf("\nERROR 15604"); getchar(); } } else{ // Check if update_in_cycle is flagged for addition if (update_in_cycle[ei][u_ptr].flag){ // Flagged for addition: means, it is // already there in original. Just copy and increment all pointers scratch[s_ptr++] = self->g_edges_in_cycles[ei][o_ptr++]; u_ptr++; } else{ // Flagged for removal: means, it is // to be skipped o_ptr++; u_ptr++; } } } // If o_ptr did not reach end: means copy all that are remaining as nothing to // update while (o_ptr < self->g_edges_in_cycles_len[ei]){ scratch[s_ptr++] = self->g_edges_in_cycles[ei][o_ptr++]; } // If u_ptr did not reach end: means all of these should have been flagged for addition while (u_ptr < update_in_cycle_len[ei]){ scratch[s_ptr++] = update_in_cycle[ei][u_ptr++].cyc; } free(self->g_edges_in_cycles[ei]); self->g_edges_in_cycles[ei] = scratch; self->g_edges_in_cycles_len[ei] = s_ptr; update_in_cycle_len[ei] = 0; update_in_cycle_max_len[ei] = 1; update_in_cycle[ei] = (update_in_cyc*)realloc(\ update_in_cycle[ei]\ , sizeof(update_in_cyc)); } update_edges_num = 0; if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &ff3); cc3 += (ff3.tv_sec - ss3.tv_sec); cc3 += (ff3.tv_nsec - ss3.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &ss4); } // Update CC with new boundaries, update Llen and Lupdated for (EDGE_ID vi = 0; vi < V_len; vi++){ EDGE_ID ci = update_V[vi].cycid; EDGE_ID li = CC[ci].Lidx; free(CC[ci].boundary); CC[ci].boundary = update_V[vi].VV; CC[ci].len = update_V[vi].V_len; Llen[li] = update_V[vi].V_len; Lupdated[li] = 1; } // Sort Llen, Lupdated, Lcycid mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); // Update C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } // Update V.Lidx for (EDGE_ID vi = 0; vi < V_len; vi++){ update_V[vi].Lidx = CC[update_V[vi].cycid].Lidx; } // Sort update_V by Lidx if (V_len > 1){ mergeSort_update_V_byLidx(update_V, 0, V_len-1); } for (EDGE_ID vi = 0; vi < V_len; vi++){ update_v_indices[vi] = update_V[vi].Lidx; } //// Sort each g_edges_in_cycles by len of cycles //for (EDGE_ID ei = 0; ei < self->g_n_valid_edges; ei++){ // // if (self->g_edges_in_cycles_len[ei] < 2) continue; // mergeSort_edges_in_cycles(self->g_edges_in_cycles[ei], CC, 0, self->g_edges_in_cycles_len[ei]-1); // //} if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &ff4); cc4 += (ff4.tv_sec - ss4.tv_sec); cc4 += (ff4.tv_nsec - ss4.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &ss5); } // Get the cases // Case 1: x is updated -> check with all with diff = 0 (this is n update_V) // CASE 2a: x is not updated + diff is 0 -> only check with updated // CASE 2ba: x is not updated + diff is not 0 + y is updated -> check with all after new diff // Case 2bb: x is not updated + diff is not 0 + y is not updated -> only check with updated case2a2bb_num = 0; case2ba_num = 0; for (EDGE_ID li = 0; li < stored_num; li++){ EDGE_ID ci = Lcycid[li]; if (Lupdated[li]) continue; // x is not updated if (!CC[ci].diff){ // diff is 0 -> only check with updated -> case 2 case2a2bb[case2a2bb_num++] = li; } else{ EDGE_ID cj = CC[ci].redw; EDGE_ID lj = CC[cj].Lidx; if (Lupdated[lj]){ // diff is not 0 and y is updated -> check with all, but diff is not set to 0 -> case 1 case2ba[case2ba_num++] = li; } else{ // diff is not 0 and y is not updated -> only check with updated -> case 2 case2a2bb[case2a2bb_num++] = li; } } } if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &ff5); cc5 += (ff5.tv_sec - ss5.tv_sec); cc5 += (ff5.tv_nsec - ss5.tv_nsec) / 1000000000.0; } //printf("\nStarting 15790"); //getchar(); ////////////////////////////////////////////////////////// //printf("\nUpdating diffs..."); // Update diffs ////////////////////////////////////////////////////////// // NOTE: updated_V is sorted by increasing Lidx at this point struct timespec start1, start2, start3; struct timespec finish1, finish2, finish3; double c1 = 0; double c2 = 0; double c3 = 0; // NEW NEW // CASE 1 //printf("\nStarting 15810"); //getchar(); if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &start1); } #pragma omp parallel for schedule(static, 50) shared(stored_num\ , CC\ , Lcycid, Lupdated\ , update_V, V_len\ ) for (EDGE_ID vi = 0; vi < V_len; vi++){ EDGE_ID li = update_V[vi].Lidx; EDGE_ID ci = Lcycid[li]; //for (EDGE_ID ci = 0; ci < stored_num; ci++){ CC[ci].diff = 0; //EDGE_ID li = CC[ci].Lidx; //printf("\ncase 1 diff before for cycle %d is %d", ci, CC[ci].diff); //// flag_case = 0 to check with all update_diff(self, li, Lupdated, 0, Lcycid, CC, stored_num); //printf("\ncase 1 diff after for cycle %d is %d", ci, CC[ci].diff); } if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish1); c1 += (finish1.tv_sec - start1.tv_sec); c1 += (finish1.tv_nsec - start1.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &start2); } // CASE 2a2bb: Only check with updated cycles #pragma omp parallel for schedule(static, 50) shared(stored_num\ , CC\ , Lcycid, Lupdated\ , case2a2bb_num, case2a2bb) for (EDGE_ID idx = 0; idx < case2a2bb_num; idx++){ EDGE_ID li = case2a2bb[idx]; //EDGE_ID ci = Lcycid[li]; //printf("\ncase 2 diff before for cycle %d is %d", ci, CC[ci].diff); // flag_case = 1 to check with only updated //update_diff(self, li, Lupdated, 1, Lcycid, CC, stored_num); minimal_CASE2(self, li, CC, Lcycid, Llen, update_v_indices, V_len); //printf("\ncase 2 diff after for cycle %d is %d", ci, CC[ci].diff); } if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish2); c2 += (finish2.tv_sec - start2.tv_sec); c2 += (finish2.tv_nsec - start2.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &start3); } // CASE 2ba #pragma omp parallel for schedule(static, 50) shared(stored_num\ , CC\ , Lcycid, Lupdated\ , case2ba, case2ba_num) for(EDGE_ID idx = 0; idx < case2ba_num; idx++){ EDGE_ID li = case2ba[idx]; EDGE_ID ci = Lcycid[li]; EDGE_ID cj = CC[ci].redw; //printf("\ncase 3 diff before for cycle %d is %d", ci, CC[ci].diff); ////////////// // CASE 2ba: x is NOT updated and diff is NOT 0 and y is updated ////////////// //printf(" Case 2ba"); EDGE_ID j = 0; EDGE_ID k = 0; EDGE_ID count = 0; while ((j < CC[ci].len) && (k < CC[cj].len)){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ j++; count++; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ k++; count++; } else{ j++; k++; } if (count >= CC[ci].len){ break; } } if (j < CC[ci].len){ count += CC[ci].len - j; } if (k < CC[cj].len){ count += CC[cj].len - k; } if (count < CC[ci].len){ CC[ci].diff = CC[ci].len - count; } else{ CC[ci].diff = 0; } // flag_case = 0 to check with all update_diff(self, li, Lupdated, 0, Lcycid, CC, stored_num); //printf("\ncase 3 diff after for cycle %d is %d", ci, CC[ci].diff); } if (!self->g_suppress_output){ clock_gettime(CLOCK_MONOTONIC, &finish3); c3 += (finish3.tv_sec - start3.tv_sec); c3 += (finish3.tv_nsec - start3.tv_nsec) / 1000000000.0; clock_gettime(CLOCK_MONOTONIC, &ff0); cc0 += (ff0.tv_sec - ss0.tv_sec); cc0 += (ff0.tv_nsec - ss0.tv_nsec) / 1000000000.0; printf("\nmax diff %d, num pairs %d, case 1 %lf, case 2a2bb %lf, case 2ba %lf, (%lf,%lf, %lf, %lf, %lf, %lf), %lf"\ , dm\ , V_len\ , c1\ , c2\ , c3\ , cc1\ , cc2\ , cc3\ , cc4\ , cc5\ , cc6\ , cc0\ ); } // Reset Lupdated for (EDGE_ID li = 0; li < stored_num; li++){ Lupdated[li] = 0; } //getchar(); } ////////////////////////////////////////////////////////////// // TESTING ////////////////////////////////////////////////////////////// // //printf("\nPress key to test"); //getchar(); //printf("\nTESTING..."); //#pragma omp parallel for schedule(static) shared(stored_num\ // , CC) //for (EDGE_ID ci = 0; ci < stored_num; ci++){ // EDGE_ID diff = 0; // // for (EDGE_ID cj = 0; cj < stored_num; cj++){ // // if (cj == ci) continue; // EDGE_ID j = 0; // EDGE_ID k = 0; // EDGE_ID count = 0; // int quit_flag = 0; // while ((j < CC[ci].len) && (k < CC[cj].len)){ // if (CC[ci].boundary[j] < CC[cj].boundary[k]){ // j++; // count++; // } // else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ // k++; // count++; // } // else{ // j++; // k++; // } // } // if (j < CC[ci].len){ // count += CC[ci].len - j; // } // if (k < CC[cj].len){ // count += CC[cj].len - k; // } // // if (count < CC[ci].len){ // if (CC[ci].len - count > diff){ // printf("\nImprovement possible by reducing ci, li %d, %d with cj, lj %d, %d!"\ // , ci, CC[ci].Lidx\ // , cj, CC[cj].Lidx); // printf("\nTESTING FAILED!!!"); // getchar(); // } // } // // } // //} //printf("\nTESTED OK."); ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// // Sort Llen, Lupdated, Lcycid mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); // Update C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } #ifdef STORE_LENGTHS_CYCLES FILE* fp1 = fopen(minimal_lens_filename, "w"); for (EDGE_ID li = 0; li < stored_num; li++){ fprintf(fp1, "%d, ", Llen[li]); } //for (EDGE_ID ci = 0; ci < stored_num; ci++){ // fprintf(fp1, "%d, ", CC[ci].len); //} fclose(fp1); #endif FILE* fp2 = fopen(filename, "w"); if (!self->g_suppress_output){ printf("\n"); } for (EDGE_ID li = 0; li < stored_num; li++){ if (Llen[li] < 5){ break; } EDGE_ID ci = Lcycid[li]; //if (li < 15) //printf("\nlen %d", Llen[li]); for (EDGE_ID nn = 0; nn < CC[ci].len; nn++){ fprintf(fp2, "%d, %d, ", self->g_edges_list[2*CC[ci].boundary[nn]]\ , self->g_edges_list[2*CC[ci].boundary[nn]+1]); } fprintf(fp2, "\n"); free(CC[ci].boundary); } fclose(fp2); free(CC); free(update_V); free(Lcycid); free(Llen); free(Lupdated); //free(update_v_indices); // free(case2ba); free(case2a2bb); free(update_edges); free(update_edges_flag); free(update_in_cycle_len); free(update_in_cycle_max_len); for (EDGE_ID ii = 0; ii < self->g_n_valid_edges; ii++){ free(update_in_cycle[ii]); } if (!self->g_suppress_output){ printf("\nDone. Press key to quit H1 cycle shortening"); } } void minimize_birth_cycles_H0_v4(filtration* self\ , cyc_info* CC\ , EDGE_ID stored_num\ , char* filename\ , char* filename2\ ){ //printf("\nNumber of cycles %d", stored_num); //getchar(); omp_set_num_threads(2*self->g_cpu_count - 1); EDGE_ID* Lcycid = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID* Llen = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID* Lupdated = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); printf("\nIntializing L, C.Lidx..."); // Step 1. Initialize L and C.Lidx for (EDGE_ID i = 0; i < stored_num; i++){ Lcycid[i] = i; Llen[i] = CC[i].len; Lupdated[i] = 0; } printf("\nSorting Llen..."); // Step 2(a): Sort Llen, Lcycid, Lupdated by Llen mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); printf("\nInitializing C.Lidx..."); // Step 2(b): Initialize C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } PAR* sorted_par = (PAR*)malloc(stored_num*sizeof(PAR)); EDGE_ID* Pcycid = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); for (EDGE_ID ci = 0; ci < stored_num; ci++){ if (CC[ci].perspair[1] != -1){ sorted_par[ci] = CC[ci].perspair[1] - CC[ci].perspair[0]; } else{ sorted_par[ci] = self->g_thresh - CC[ci].perspair[0]; } Pcycid[ci] = ci; } // SORT temp_par by pers barcode as follows: // Sorted in decreasing order of parameter where: // For dead features: parameter = death - birth // For undead features: parameter = thresh - birth mergeSort_temp_par(sorted_par, Pcycid, 0, stored_num-1); for (EDGE_ID pi = 0; pi < stored_num; pi++){ EDGE_ID ci = Pcycid[pi]; while(1){ EDGE_ID li = CC[ci].Lidx; CC[ci].diff = 0; for (EDGE_ID lj = li + 1; lj < stored_num; lj++){ if (Llen[lj] < CC[ci].diff) break; EDGE_ID cj = Lcycid[lj]; EDGE_ID j = 0; EDGE_ID k = 0; EDGE_ID count = 0; while ((j < CC[ci].len) && (k < CC[cj].len)){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ j++; count++; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ k++; count++; } else{ j++; k++; } } if (j < CC[ci].len){ count += CC[ci].len - j; } if (k < CC[cj].len){ count += CC[cj].len - k; } if (count >= CC[ci].len - CC[ci].diff){ continue; } CC[ci].redw = cj; CC[ci].diff = CC[ci].len - count; } if (!CC[ci].diff){ printf("\nFinal new len of (%lf, %lf) is %d"\ , CC[ci].perspair[0]\ , CC[ci].perspair[1]\ , CC[ci].len); getchar(); break; } EDGE_ID j = 0; EDGE_ID k = 0; EDGE_ID count = 0; EDGE_ID cj = CC[ci].redw; printf("\nreducing %d (len %d) with %d (len %d, (%lf, %lf))"\ , ci\ , CC[ci].len\ , cj\ , CC[cj].len\ , CC[cj].perspair[0]\ , CC[cj].perspair[1]\ ); EDGE_ID* scratch = (EDGE_ID*)malloc((CC[ci].len+CC[cj].len)*sizeof(EDGE_ID)); while ((j < CC[ci].len) && (k < CC[cj].len)){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ scratch[count++] = CC[ci].boundary[j++]; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ scratch[count++] = CC[cj].boundary[k++]; } else{ j++; k++; } } while (j < CC[ci].len){ scratch[count++] = CC[ci].boundary[j++]; } while (k < CC[cj].len){ scratch[count++] = CC[cj].boundary[k++]; } free(CC[ci].boundary); printf("\nfor pers pair (%lf, %lf), Old len is %d and new len is %d"\ , CC[ci].perspair[0]\ , CC[ci].perspair[1]\ , CC[ci].len\ , count); CC[ci].boundary = scratch; CC[ci].len = count; Llen[ci] = count; printf("\nUpdate lengths"); // Sort Llen, Lupdated, Lcycid mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); // Update C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } } } } void minimal_CASE1(EDGE_ID li, cyc_info* CC, EDGE_ID* Lcycid, EDGE_ID* Llen, EDGE_ID stored_num){ EDGE_ID ci = Lcycid[li]; //CC[ci].diff = 0; for (EDGE_ID lj = li + 1; lj < stored_num; lj++){ //for (EDGE_ID lj = 0; lj < stored_num; lj++){ if (Llen[lj] < CC[ci].diff){ break; } //if (lj == li) continue; EDGE_ID cj = Lcycid[lj]; EDGE_ID j = 0; EDGE_ID k = 0; EDGE_ID count = 0; int quit_flag = 0; while ((j < CC[ci].len) && (k < CC[cj].len)){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ j++; count++; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ k++; count++; } else{ j++; k++; } if (count >= CC[ci].len){ quit_flag = 1; break; } if ((CC[ci].len - count) <= CC[ci].diff){ quit_flag = 1; break; } } if (quit_flag){ continue; } if (j < CC[ci].len){ count += CC[ci].len - j; } if (k < CC[cj].len){ count += CC[cj].len - k; } // NEED TO CHECK LOGIC HERE!!!!!!!!!!!!!!!!!!!!!! if (count >= CC[ci].len){ continue; } // NEED TO CHECK THIS <= OR < !!!!!!!!!!!!!!!! if ((CC[ci].len - count) <= CC[ci].diff){ continue; } CC[ci].diff = CC[ci].len - count; CC[ci].redw = cj; //printf("\ncase1 updating diff to %d", CC[ci].diff); //getchar(); } } void minimal_CASE2(filtration* self, EDGE_ID li, cyc_info* CC, EDGE_ID* Lcycid, EDGE_ID* Llen\ , EDGE_ID* update_v_indices, EDGE_ID V_len){ if (update_v_indices[V_len-1] <= li) return; EDGE_ID idx = bin_search_min_greater_updated_V_byLidx(update_v_indices\ , 0, V_len-1\ , li\ , V_len); EDGE_ID ci = Lcycid[li]; for (EDGE_ID vj = idx; vj < V_len; vj++){ EDGE_ID lj = update_v_indices[vj]; if (lj <= li) continue; if (Llen[lj] < CC[ci].diff){ break; } EDGE_ID cj = Lcycid[lj]; //if (CC[cj].perspair[0] > CC[ci].perspair[0]){ // continue; //} // CHECK BIRTH THRESH //if (CC[cj].updated_birth > self->g_cycle_min_birth_thresh){ // continue; //} EDGE_ID j = 0; EDGE_ID k = 0; EDGE_ID count = 0; EDGE_ID common = 0; int quit_flag = 0; while ((j < CC[ci].len) && (k < CC[cj].len)){ if (CC[ci].boundary[j] < CC[cj].boundary[k]){ j++; count++; } else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ k++; count++; } else{ j++; k++; } if (count >= CC[ci].len){ quit_flag = 1; break; } if ((CC[ci].len - count) <= CC[ci].diff){ quit_flag = 1; break; } } if (quit_flag){ continue; } if (j < CC[ci].len){ count += CC[ci].len - j; } if (k < CC[cj].len){ count += CC[cj].len - k; } // NEED TO CHECK LOGIC HERE!!!!!!!!!!!!!!!!!!!!!! if (count >= CC[ci].len){ continue; } // NEED TO CHECK LOGIC HERE!!!!!!!!!!!!!!!!!!!!!! if ((CC[ci].len - count) <= CC[ci].diff){ continue; } CC[ci].diff = CC[ci].len - count; CC[ci].redw = cj; } } void shuffle_cyc(cyc_info* CC, EDGE_ID num){ int n = (int)num; srand((unsigned)time(NULL)); for (int i = 0; i < n - 1; i++) { size_t j = i + rand() / (RAND_MAX / (n - i) + 1); cyc_info t = CC[j]; CC[j] = CC[i]; CC[i] = t; } } void update_diff(filtration* self, EDGE_ID li, EDGE_ID* Lupdated, int flag_case\ , EDGE_ID* Lcycid, cyc_info* CC, EDGE_ID stored_num){ EDGE_ID ci = Lcycid[li]; EDGE_ID* cj_diff = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); EDGE_ID max_diff = 0; for (EDGE_ID idx = 0; idx < CC[ci].len; idx++){ EDGE_ID edge = CC[ci].boundary[idx]; for (EDGE_ID idx2 = 0; idx2 < self->g_edges_in_cycles_len[edge]; idx2++){ EDGE_ID cj = self->g_edges_in_cycles[edge][idx2]; //if (CC[cj].perspair[0] > CC[ci].perspair[0]){ // continue; //} // CHECK BIRTH THRESH //if (CC[cj].updated_birth > self->g_cycle_min_birth_thresh){ // continue; //} EDGE_ID lj = CC[cj].Lidx; //if (CC[cj].len < max_diff) break; if (lj <= li) continue; if (CC[cj].len < CC[ci].diff) continue; if (flag_case){ if (!Lupdated[lj]) continue; } cj_diff[cj] += 2; if (CC[cj].len < cj_diff[cj]){ if ((cj_diff[cj] - CC[cj].len) > CC[ci].diff){ CC[ci].diff = cj_diff[cj] - CC[cj].len; CC[ci].redw = cj; max_diff = CC[ci].len + CC[cj].len - cj_diff[cj]; } } } } free(cj_diff); } void find_first_diff(filtration* self, EDGE_ID li, EDGE_ID* Lupdated\ , EDGE_ID* Lcycid, cyc_info* CC, EDGE_ID stored_num){ EDGE_ID ci = Lcycid[li]; EDGE_ID* cj_diff = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); for (EDGE_ID idx = 0; idx < CC[ci].len; idx++){ EDGE_ID edge = CC[ci].boundary[idx]; for (EDGE_ID idx2 = 0; idx2 < self->g_edges_in_cycles_len[edge]; idx2++){ EDGE_ID cj = self->g_edges_in_cycles[edge][idx2]; EDGE_ID lj = CC[cj].Lidx; if (CC[cj].len < CC[ci].diff) break; if (lj <= li) continue; cj_diff[cj] += 2; if (CC[cj].len < cj_diff[cj]){ if ((cj_diff[cj] - CC[cj].len) > CC[ci].diff){ CC[ci].diff = cj_diff[cj] - CC[cj].len; CC[ci].redw = cj; } } } } free(cj_diff); } void minimize_birth_cycles_H1_v2(filtration* self\ , cyc_info_H2* CC\ , EDGE_ID stored_num\ , char* filename\ , char* lens_filename\ , char* minimal_lens_filename\ ){ //, char* filename2\ if (!self->g_suppress_output){ printf("\nNumber of cycles %d", stored_num); } #ifdef STORE_LENGTHS_CYCLES FILE* fp0 = fopen(lens_filename, "w"); for (EDGE_ID ci = 0; ci < stored_num; ci++){ fprintf(fp0, "%d, ", CC[ci].len); if (!self->g_reduce_cyc_lengths){ free(CC[ci].boundary); } } fclose(fp0); #endif if (!self->g_reduce_cyc_lengths){ free(CC); return; } omp_set_num_threads(2*self->g_cpu_count - 1); EDGE_ID* Lcycid = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID* Llen = (EDGE_ID*)malloc(stored_num*sizeof(EDGE_ID)); EDGE_ID* Lupdated = (EDGE_ID*)calloc(stored_num, sizeof(EDGE_ID)); // Step 1. Initialize L and C.Lidx for (EDGE_ID i = 0; i < stored_num; i++){ Lcycid[i] = i; Llen[i] = CC[i].len; Lupdated[i] = 0; } //printf("\nSorting Llen..."); // Step 2(a): Sort Llen, Lcycid, Lupdated by Llen mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); //printf("\nInitializing C.Lidx..."); // Step 2(b): Initialize C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } // Define V that will store summations to be done EDGE_ID V_len = 0; EDGE_ID V_max_len = 10; min_update_V_H2* update_V = (min_update_V_H2*)malloc(V_max_len*sizeof(min_update_V_H2)); EDGE_ID it_counter = 0; // Step 4: Loop for minimization while (1){ if (!self->g_suppress_output){ printf("\n\nIteration %d", it_counter++); } // Step 4(a): Find max diff EDGE_ID dm = 1; V_len = 0; for (EDGE_ID li = 0; li < stored_num; li++){ //printf("\nli %d", li); if (Llen[li] < dm) break; int add_flag = 0; EDGE_ID ci = Lcycid[li]; for (EDGE_ID lj = li + 1; lj < stored_num; lj++){ if (Llen[lj] < dm) break; //printf("\nlj %d", lj); EDGE_ID cj = Lcycid[lj]; EDGE_ID i = 0; EDGE_ID j = 0; EDGE_ID count = 0; int quit_flag = 0; while (i < CC[ci].len && j < CC[cj].len){ int compare; if (CC[ci].boundary[i].key1 < CC[cj].boundary[j].key1){ compare = 1; } else if (CC[ci].boundary[i].key1 > CC[cj].boundary[j].key1){ compare = 0; } else{ if (CC[ci].boundary[i].key2 < CC[cj].boundary[j].key2){ compare = 1; } else if (CC[ci].boundary[i].key2 > CC[cj].boundary[j].key2){ compare = 0; } else{ compare = -1; } } if (compare == 1){ i++; count++; } else if (!compare){ j++; count++; } else{ i++; j++; } if (count > CC[ci].len - dm){ quit_flag = 1; break; } } if (quit_flag) continue; if (i < CC[ci].len){ count += CC[ci].len - i; } if (j < CC[cj].len){ count += CC[cj].len - j; } if (count > CC[ci].len - dm){ continue; } //printf("\nREACHED HERE"); //getchar(); if (CC[ci].len - count > dm){ dm = CC[ci].len - count; update_V[0].cycid = ci; CC[ci].redw = cj; V_len = 1; add_flag = 1; } else if ((CC[ci].len - count == dm) && (!add_flag)){ add_flag = 1; update_V[V_len++].cycid = ci; CC[ci].redw = cj; if (V_len == V_max_len){ V_max_len += 100; update_V = (min_update_V_H2*)realloc(update_V\ , V_max_len*sizeof(min_update_V_H2)); } } } } if (!V_len){ //printf("\nDiff 0. EXITING."); break; } if (!self->g_suppress_output){ printf("\nmaxdiff %d, num pairs %d", dm, V_len); } #pragma omp parallel for schedule(static, 50) shared(update_V, CC) for (EDGE_ID vi = 0; vi < V_len; vi++){ //if (vi % 1000 == 0){ //printf("\nreducing %d", vi); //} EDGE_ID ci = update_V[vi].cycid; EDGE_ID cj = CC[ci].redw; //printf("\nReducing %d with %d", ci, cj); simplex* scratch = (simplex*)malloc((CC[ci].len + CC[cj].len)*sizeof(simplex)); EDGE_ID edge; EDGE_ID i = 0; EDGE_ID j = 0; EDGE_ID count = 0; while ((i < CC[ci].len) && (j < CC[cj].len)){ int compare; if (CC[ci].boundary[i].key1 < CC[cj].boundary[j].key1){ compare = 1; } else if (CC[ci].boundary[i].key1 > CC[cj].boundary[j].key1){ compare = 0; } else{ if (CC[ci].boundary[i].key2 < CC[cj].boundary[j].key2){ compare = 1; } else if (CC[ci].boundary[i].key2 > CC[cj].boundary[j].key2){ compare = 0; } else{ compare = -1; } } if (compare==1){ scratch[count++] = CC[ci].boundary[i++]; } else if (!compare){ scratch[count++] = CC[cj].boundary[j++]; } else{ i++; j++; } } // update_in_cyc will have unique while (i < CC[ci].len){ // No change scratch[count++] = CC[ci].boundary[i++]; } while (j < CC[cj].len){ scratch[count++] = CC[cj].boundary[j++]; } scratch = (simplex*)realloc(scratch, count*sizeof(simplex)); update_V[vi].VV = scratch; update_V[vi].V_len = count; } // Update CC with new boundaries, update Llen and Lupdated for (EDGE_ID vi = 0; vi < V_len; vi++){ EDGE_ID ci = update_V[vi].cycid; EDGE_ID li = CC[ci].Lidx; free(CC[ci].boundary); CC[ci].boundary = update_V[vi].VV; CC[ci].len = update_V[vi].V_len; Llen[li] = update_V[vi].V_len; Lupdated[li] = 1; } // Sort Llen, Lupdated, Lcycid mergeSort_Llen(Llen, Lcycid, Lupdated, 0, stored_num - 1); // Update C.Lidx for (EDGE_ID li = 0; li < stored_num; li++){ CC[Lcycid[li]].Lidx = li; } } ////////////////////////////////////////////////////////////// // TESTING ////////////////////////////////////////////////////////////// // //printf("\nPress key to test"); //getchar(); //printf("\nTESTING..."); //#pragma omp parallel for schedule(static) shared(stored_num\ // , CC) //for (EDGE_ID ci = 0; ci < stored_num; ci++){ // EDGE_ID diff = 0; // // for (EDGE_ID cj = 0; cj < stored_num; cj++){ // // if (cj == ci) continue; // EDGE_ID j = 0; // EDGE_ID k = 0; // EDGE_ID count = 0; // int quit_flag = 0; // while ((j < CC[ci].len) && (k < CC[cj].len)){ // if (CC[ci].boundary[j] < CC[cj].boundary[k]){ // j++; // count++; // } // else if (CC[ci].boundary[j] > CC[cj].boundary[k]){ // k++; // count++; // } // else{ // j++; // k++; // } // } // if (j < CC[ci].len){ // count += CC[ci].len - j; // } // if (k < CC[cj].len){ // count += CC[cj].len - k; // } // // if (count < CC[ci].len){ // if (CC[ci].len - count > diff){ // printf("\nImprovement possible by reducing ci, li %d, %d with cj, lj %d, %d!"\ // , ci, CC[ci].Lidx\ // , cj, CC[cj].Lidx); // printf("\nTESTING FAILED!!!"); // getchar(); // } // } // // } // //} //printf("\nTESTED OK."); ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// #ifdef STORE_LENGTHS_CYCLES FILE* fp1 = fopen(minimal_lens_filename, "w"); for (EDGE_ID ci = 0; ci < stored_num; ci++){ fprintf(fp1, "%d, ", CC[ci].len); } fclose(fp1); #endif FILE* fp2 = fopen(filename, "w"); for (EDGE_ID li = 0; li < stored_num; li++){ EDGE_ID ci = Lcycid[li]; //if (li < 15) //printf("\nlen %d", Llen[li]); for (EDGE_ID nn = 0; nn < CC[ci].len; nn++){ fprintf(fp2, "%d, %d, %d, ", self->g_edges_list[2*CC[ci].boundary[nn].key1]\ , self->g_edges_list[2*CC[ci].boundary[nn].key1+1]\ , CC[ci].boundary[nn].key2\ ); } fprintf(fp2, "\n"); free(CC[ci].boundary); } fclose(fp2); //} free(CC); free(update_V); free(Lcycid); free(Llen); free(Lupdated); } //static PyMethodDef DoryMethods[] = { // // {"compute_PH", compute_PH, METH_VARARGS, "Compute PH"}, // {NULL, NULL, 0, NULL} // //}; // //static struct PyModuleDef dorymodule = { // PyModuleDef_HEAD_INIT, // "pydory", /* name of module*/ // NULL, /* documentation */ // -1, /* ??? */ // DoryMethods //}; // // //PyMODINIT_FUNC PyInit_pydory(void){ // return PyModule_Create(&dorymodule); //}
keyring_fmt_plug.c
/* GNOME Keyring cracker patch for JtR. Hacked together during Monsoon of * 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>, * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without modification, * are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_keyring; #elif FMT_REGISTERS_H john_register_one(&fmt_keyring); #else #include <string.h> #include <assert.h> #include <errno.h> #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #ifdef __MIC__ #define OMP_SCALE 32 #else #define OMP_SCALE 64 #endif // __MIC__ #endif // OMP_SCALE #endif // _OPENMP #include "arch.h" //#undef _OPENMP //#undef SIMD_COEF_32 #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "md5.h" #include "sha2.h" #include "aes.h" #include "johnswap.h" #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "keyring" #define FORMAT_NAME "GNOME Keyring" #define FORMAT_TAG "$keyring$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "SHA256 AES " SHA256_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 0 #define SALT_SIZE sizeof(*cur_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(int) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_32*SIMD_PARA_SHA256) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_32*SIMD_PARA_SHA256) #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32*4 ) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define SALTLEN 8 typedef unsigned char guchar; typedef unsigned int guint; typedef int gint; static struct fmt_tests keyring_tests[] = { {"$keyring$db1b562e453a0764*3221*16*0*02b5c084e4802369c42507300f2e5e56", "openwall"}, {"$keyring$4f3f1557a7da17f5*2439*144*0*12215fabcff6782aa23605ab2cd843f7be9477b172b615eaa9130836f189d32ffda2e666747378f09c6e76ad817154daae83a36c0a0a35f991d40bcfcba3b7807ef57a0ce4c7f835bf34c6e358f0d66aa048d73dacaaaf6d7fa4b3510add6b88cc237000ff13cb4dbd132db33be3ea113bedeba80606f86662cc226af0dad789c703a7df5ad8700542e0f7a5e1f10cf0", "password"}, {NULL} }; static struct custom_salt { unsigned int iterations; unsigned char salt[SALTLEN]; unsigned int crypto_size; unsigned int inlined; unsigned char ct[LINE_BUFFER_SIZE / 2]; /* after hex conversion */ } *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked; static int any_cracked; static size_t cracked_size; static void init(struct fmt_main *self) { #if defined (_OPENMP) int omp_t; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; self->params.max_keys_per_crypt *= omp_t * OMP_SCALE; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); any_cracked = 0; cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt; cracked = mem_calloc(cracked_size, 1); } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } static int looks_like_nice_int(char *p) { // reasonability check + avoids atoi's UB if (strlen(p) > 9) return 0; for (; *p; p++) if (*p < '0' || *p > '9') return 0; return 1; } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; int ctlen, extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; if (keeptr == NULL) goto err; ctcopy += FORMAT_TAG_LEN; if ((p = strtokm(ctcopy, "*")) == NULL) /* salt */ goto err; if (hexlenl(p, &extra) != SALTLEN * 2 || extra) goto err; while (*p) if (atoi16[ARCH_INDEX(*p++)] == 0x7f) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iterations */ goto err; if (!looks_like_nice_int(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* crypto size */ goto err; if (!looks_like_nice_int(p)) goto err; ctlen = atoi(p); if (ctlen > sizeof(cur_salt->ct)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* inlined - unused? TODO */ goto err; if (!looks_like_nice_int(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* ciphertext */ goto err; if (ctlen > LINE_BUFFER_SIZE) goto err; if (hexlenl(p, &extra) != ctlen * 2 || extra) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += FORMAT_TAG_LEN; /* skip over "$keyring$" */ cur_salt = mem_alloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); p = strtokm(ctcopy, "*"); for (i = 0; i < SALTLEN; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.iterations = atoi(p); p = strtokm(NULL, "*"); cs.crypto_size = atoi(p); p = strtokm(NULL, "*"); cs.inlined = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.crypto_size; i++) cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } #ifdef SIMD_COEF_32 static void symkey_generate_simple(int index, unsigned char *salt, int n_salt, int iterations, unsigned char key[MAX_KEYS_PER_CRYPT][32], unsigned char iv[MAX_KEYS_PER_CRYPT][32]) { SHA256_CTX ctx; unsigned char digest[32], _IBuf[64*MAX_KEYS_PER_CRYPT+MEM_ALIGN_SIMD], *keys; uint32_t *keys32; unsigned int i, j; keys = (unsigned char*)mem_align(_IBuf, MEM_ALIGN_SIMD); memset(keys, 0, 64*MAX_KEYS_PER_CRYPT); keys32 = (uint32_t*)keys; // use oSSL to do first crypt, and marshal into SIMD buffers. for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { SHA256_Init(&ctx); SHA256_Update(&ctx, saved_key[index+i], strlen(saved_key[index+i])); SHA256_Update(&ctx, salt, n_salt); SHA256_Final(digest, &ctx); for (j = 0; j < 32; ++j) keys[GETPOS(j, i)] = digest[j]; keys[GETPOS(j, i)] = 0x80; // 32 bytes is 256 bits (0x100, simply put a 1 into offset 62) keys[GETPOS(62, i)] = 1; } // the 'simple' inner loop in SIMD. for (i = 1; i < iterations; ++i) SIMDSHA256body(keys, keys32, NULL, SSEi_MIXED_IN|SSEi_OUTPUT_AS_INP_FMT); // marshal data back into flat buffers. for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { uint32_t *Optr32 = (uint32_t*)(key[i]); uint32_t *Iptr32 = &keys32[(i/SIMD_COEF_32)*SIMD_COEF_32*16 + (i%SIMD_COEF_32)]; for (j = 0; j < 4; ++j) Optr32[j] = JOHNSWAP(Iptr32[j*SIMD_COEF_32]); Optr32 = (uint32_t*)(iv[i]); for (j = 0; j < 4; ++j) Optr32[j] = JOHNSWAP(Iptr32[(j+4)*SIMD_COEF_32]); } } #else static void symkey_generate_simple(int index, unsigned char *salt, int n_salt, int iterations, unsigned char key[MAX_KEYS_PER_CRYPT][32], unsigned char iv[MAX_KEYS_PER_CRYPT][32]) { SHA256_CTX ctx; unsigned char digest[32]; int i; SHA256_Init(&ctx); SHA256_Update(&ctx, saved_key[index], strlen(saved_key[index])); SHA256_Update(&ctx, salt, n_salt); SHA256_Final(digest, &ctx); for (i = 1; i < iterations; ++i) { SHA256_Init(&ctx); SHA256_Update(&ctx, digest, 32); SHA256_Final(digest, &ctx); } memcpy(key[0], digest, 16); memcpy(iv[0], &digest[16], 16); } #endif static void decrypt_buffer(unsigned char buffers[MAX_KEYS_PER_CRYPT][sizeof(cur_salt->ct)], int index) { unsigned char key[MAX_KEYS_PER_CRYPT][32]; unsigned char iv[MAX_KEYS_PER_CRYPT][32]; AES_KEY akey; unsigned int i, len = cur_salt->crypto_size; unsigned char *salt = cur_salt->salt; int iterations = cur_salt->iterations; symkey_generate_simple(index, salt, 8, iterations, key, iv); for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { memset(&akey, 0, sizeof(AES_KEY)); if (AES_set_decrypt_key(key[i], 128, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); } AES_cbc_encrypt(cur_salt->ct, buffers[i], len, &akey, iv[i], AES_DECRYPT); } } static int verify_decrypted_buffer(unsigned char *buffer, int len) { guchar digest[16]; MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, buffer + 16, len - 16); MD5_Final(digest, &ctx); return memcmp(buffer, digest, 16) == 0; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index+=MAX_KEYS_PER_CRYPT) { int i; unsigned char (*buffers)[sizeof(cur_salt->ct)]; // This is too big to be on stack. See #1292. buffers = mem_alloc(MAX_KEYS_PER_CRYPT * sizeof(*buffers)); decrypt_buffer(buffers, index); for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { if (verify_decrypted_buffer(buffers[i], cur_salt->crypto_size)) { cracked[index+i] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } MEM_FREE(buffers); } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return cracked[index]; } static void keyring_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return my_salt->iterations; } struct fmt_main fmt_keyring = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", }, { FORMAT_TAG }, keyring_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, keyring_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
common.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_UTILS_COMMON_FUN_H_ #define LIGHTGBM_UTILS_COMMON_FUN_H_ #include <LightGBM/utils/log.h> #include <LightGBM/utils/openmp_wrapper.h> #include <limits> #include <string> #include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <cstdio> #include <functional> #include <iomanip> #include <iterator> #include <map> #include <memory> #include <sstream> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #ifdef _MSC_VER #include <intrin.h> #pragma intrinsic(_BitScanReverse) #endif #if defined(_MSC_VER) #include <malloc.h> #elif MM_MALLOC #include <mm_malloc.h> // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html // https://www.oreilly.com/library/view/mac-os-x/0596003560/ch05s01s02.html #elif defined(__GNUC__) && defined(HAVE_MALLOC_H) #include <malloc.h> #define _mm_malloc(a, b) memalign(b, a) #define _mm_free(a) free(a) #else #include <stdlib.h> #define _mm_malloc(a, b) malloc(a) #define _mm_free(a) free(a) #endif namespace LightGBM { namespace Common { inline static char tolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } inline static std::string Trim(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1); str.erase(0, str.find_first_not_of(" \f\n\r\t\v")); return str; } inline static std::string RemoveQuotationSymbol(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of("'\"") + 1); str.erase(0, str.find_first_not_of("'\"")); return str; } inline static bool StartsWith(const std::string& str, const std::string prefix) { if (str.substr(0, prefix.size()) == prefix) { return true; } else { return false; } } inline static std::vector<std::string> Split(const char* c_str, char delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == delimiter) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> SplitBrackets(const char* c_str, char left_delimiter, char right_delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; bool open = false; while (pos < str.length()) { if (str[pos] == left_delimiter) { open = true; ++pos; i = pos; } else if (str[pos] == right_delimiter && open) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } open = false; ++pos; } else { ++pos; } } return ret; } inline static std::vector<std::string> SplitLines(const char* c_str) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == '\n' || str[pos] == '\r') { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } // skip the line endings while (str[pos] == '\n' || str[pos] == '\r') ++pos; // new begin i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { bool met_delimiters = false; for (int j = 0; delimiters[j] != '\0'; ++j) { if (str[pos] == delimiters[j]) { met_delimiters = true; break; } } if (met_delimiters) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } template<typename T> inline static const char* Atoi(const char* p, T* out) { int sign; T value; while (*p == ' ') { ++p; } sign = 1; if (*p == '-') { sign = -1; ++p; } else if (*p == '+') { ++p; } for (value = 0; *p >= '0' && *p <= '9'; ++p) { value = value * 10 + (*p - '0'); } *out = static_cast<T>(sign * value); while (*p == ' ') { ++p; } return p; } template<typename T> inline static double Pow(T base, int power) { if (power < 0) { return 1.0 / Pow(base, -power); } else if (power == 0) { return 1; } else if (power % 2 == 0) { return Pow(base*base, power / 2); } else if (power % 3 == 0) { return Pow(base*base*base, power / 3); } else { return base * Pow(base, power - 1); } } inline static const char* Atof(const char* p, double* out) { int frac; double sign, value, scale; *out = NAN; // Skip leading white space, if any. while (*p == ' ') { ++p; } // Get sign, if any. sign = 1.0; if (*p == '-') { sign = -1.0; ++p; } else if (*p == '+') { ++p; } // is a number if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') { // Get digits before decimal point or exponent, if any. for (value = 0.0; *p >= '0' && *p <= '9'; ++p) { value = value * 10.0 + (*p - '0'); } // Get digits after decimal point, if any. if (*p == '.') { double right = 0.0; int nn = 0; ++p; while (*p >= '0' && *p <= '9') { right = (*p - '0') + right * 10.0; ++nn; ++p; } value += right / Pow(10.0, nn); } // Handle exponent, if any. frac = 0; scale = 1.0; if ((*p == 'e') || (*p == 'E')) { uint32_t expon; // Get sign of exponent, if any. ++p; if (*p == '-') { frac = 1; ++p; } else if (*p == '+') { ++p; } // Get digits of exponent, if any. for (expon = 0; *p >= '0' && *p <= '9'; ++p) { expon = expon * 10 + (*p - '0'); } if (expon > 308) expon = 308; // Calculate scaling factor. while (expon >= 50) { scale *= 1E50; expon -= 50; } while (expon >= 8) { scale *= 1E8; expon -= 8; } while (expon > 0) { scale *= 10.0; expon -= 1; } } // Return signed and scaled floating point result. *out = sign * (frac ? (value / scale) : (value * scale)); } else { size_t cnt = 0; while (*(p + cnt) != '\0' && *(p + cnt) != ' ' && *(p + cnt) != '\t' && *(p + cnt) != ',' && *(p + cnt) != '\n' && *(p + cnt) != '\r' && *(p + cnt) != ':') { ++cnt; } if (cnt > 0) { std::string tmp_str(p, cnt); std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower); if (tmp_str == std::string("na") || tmp_str == std::string("nan") || tmp_str == std::string("null")) { *out = NAN; } else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) { *out = sign * 1e308; } else { Log::Fatal("Unknown token %s in data file", tmp_str.c_str()); } p += cnt; } } while (*p == ' ') { ++p; } return p; } inline static bool AtoiAndCheck(const char* p, int* out) { const char* after = Atoi(p, out); if (*after != '\0') { return false; } return true; } inline static bool AtofAndCheck(const char* p, double* out) { const char* after = Atof(p, out); if (*after != '\0') { return false; } return true; } inline static unsigned CountDecimalDigit32(uint32_t n) { #if defined(_MSC_VER) || defined(__GNUC__) static const uint32_t powers_of_10[] = { 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; #ifdef _MSC_VER // NOLINTNEXTLINE unsigned long i = 0; _BitScanReverse(&i, n | 1); uint32_t t = (i + 1) * 1233 >> 12; #elif __GNUC__ uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12; #endif return t - (n < powers_of_10[t]) + 1; #else if (n < 10) return 1; if (n < 100) return 2; if (n < 1000) return 3; if (n < 10000) return 4; if (n < 100000) return 5; if (n < 1000000) return 6; if (n < 10000000) return 7; if (n < 100000000) return 8; if (n < 1000000000) return 9; return 10; #endif } inline static void Uint32ToStr(uint32_t value, char* buffer) { const char kDigitsLut[200] = { '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8', '4', '9', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7', '5', '8', '5', '9', '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9', '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', '8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9' }; unsigned digit = CountDecimalDigit32(value); buffer += digit; *buffer = '\0'; while (value >= 100) { const unsigned i = (value % 100) << 1; value /= 100; *--buffer = kDigitsLut[i + 1]; *--buffer = kDigitsLut[i]; } if (value < 10) { *--buffer = static_cast<char>(value) + '0'; } else { const unsigned i = value << 1; *--buffer = kDigitsLut[i + 1]; *--buffer = kDigitsLut[i]; } } inline static void Int32ToStr(int32_t value, char* buffer) { uint32_t u = static_cast<uint32_t>(value); if (value < 0) { *buffer++ = '-'; u = ~u + 1; } Uint32ToStr(u, buffer); } inline static void DoubleToStr(double value, char* buffer, size_t buffer_len) { #ifdef _MSC_VER int num_chars = sprintf_s(buffer, buffer_len, "%.17g", value); #else int num_chars = snprintf(buffer, buffer_len, "%.17g", value); #endif CHECK_GE(num_chars, 0); } inline static const char* SkipSpaceAndTab(const char* p) { while (*p == ' ' || *p == '\t') { ++p; } return p; } inline static const char* SkipReturn(const char* p) { while (*p == '\n' || *p == '\r' || *p == ' ') { ++p; } return p; } template<typename T, typename T2> inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) { std::vector<T2> ret(arr.size()); for (size_t i = 0; i < arr.size(); ++i) { ret[i] = static_cast<T2>(arr[i]); } return ret; } template<typename T, bool is_float, bool is_unsign> struct __TToStringHelperFast { void operator()(T value, char* buffer, size_t) const { Int32ToStr(value, buffer); } }; template<typename T> struct __TToStringHelperFast<T, true, false> { void operator()(T value, char* buffer, size_t buf_len) const { #ifdef _MSC_VER int num_chars = sprintf_s(buffer, buf_len, "%g", value); #else int num_chars = snprintf(buffer, buf_len, "%g", value); #endif CHECK_GE(num_chars, 0); } }; template<typename T> struct __TToStringHelperFast<T, false, true> { void operator()(T value, char* buffer, size_t) const { Uint32ToStr(value, buffer); } }; template<typename T> inline static std::string ArrayToStringFast(const std::vector<T>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } __TToStringHelperFast<T, std::is_floating_point<T>::value, std::is_unsigned<T>::value> helper; const size_t buf_len = 16; std::vector<char> buffer(buf_len); std::stringstream str_buf; helper(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { helper(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } inline static std::string ArrayToString(const std::vector<double>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } const size_t buf_len = 32; std::vector<char> buffer(buf_len); std::stringstream str_buf; DoubleToStr(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { DoubleToStr(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; Atoi(str.c_str(), &ret); return ret; } }; template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { return static_cast<T>(std::stod(str)); } }; template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T> inline static std::vector<std::vector<T>> StringToArrayofArrays( const std::string& str, char left_bracket, char right_bracket, char delimiter) { std::vector<std::string> strs = SplitBrackets(str.c_str(), left_bracket, right_bracket); std::vector<std::vector<T>> ret; for (const auto& s : strs) { ret.push_back(StringToArray<T>(s, delimiter)); } return ret; } template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = Split(str.c_str(), ' '); CHECK_EQ(strs.size(), static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return Atoi(p, out); } }; template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out = static_cast<T>(tmp); return ret; } }; template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[0]; for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } template<> inline std::string Join<int8_t>(const std::vector<int8_t>& strs, const char* delimiter) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << static_cast<int16_t>(strs[0]); for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << static_cast<int16_t>(strs[i]); } return str_buf.str(); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) { if (end - start <= 0) { return std::string(""); } start = std::min(start, static_cast<size_t>(strs.size()) - 1); end = std::min(end, static_cast<size_t>(strs.size())); std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[start]; for (size_t i = start + 1; i < end; ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } inline static int64_t Pow2RoundUp(int64_t x) { int64_t t = 1; for (int i = 0; i < 64; ++i) { if (t >= x) { return t; } t <<= 1; } return 0; } /*! * \brief Do inplace softmax transformation on p_rec * \param p_rec The input/output vector of the values. */ inline static void Softmax(std::vector<double>* p_rec) { std::vector<double> &rec = *p_rec; double wmax = rec[0]; for (size_t i = 1; i < rec.size(); ++i) { wmax = std::max(rec[i], wmax); } double wsum = 0.0f; for (size_t i = 0; i < rec.size(); ++i) { rec[i] = std::exp(rec[i] - wmax); wsum += rec[i]; } for (size_t i = 0; i < rec.size(); ++i) { rec[i] /= static_cast<double>(wsum); } } inline static void Softmax(const double* input, double* output, int len) { double wmax = input[0]; for (int i = 1; i < len; ++i) { wmax = std::max(input[i], wmax); } double wsum = 0.0f; for (int i = 0; i < len; ++i) { output[i] = std::exp(input[i] - wmax); wsum += output[i]; } for (int i = 0; i < len; ++i) { output[i] /= static_cast<double>(wsum); } } template<typename T> std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) { std::vector<const T*> ret; for (auto t = input.begin(); t !=input.end(); ++t) { ret.push_back(t->get()); } return ret; } template<typename T1, typename T2> inline static void SortForPair(std::vector<T1>* keys, std::vector<T2>* values, size_t start, bool is_reverse = false) { std::vector<std::pair<T1, T2>> arr; auto& ref_key = *keys; auto& ref_value = *values; for (size_t i = start; i < keys->size(); ++i) { arr.emplace_back(ref_key[i], ref_value[i]); } if (!is_reverse) { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first < b.first; }); } else { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first > b.first; }); } for (size_t i = start; i < arr.size(); ++i) { ref_key[i] = arr[i].first; ref_value[i] = arr[i].second; } } template <typename T> inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>* data) { std::vector<T*> ptr(data->size()); auto& ref_data = *data; for (size_t i = 0; i < data->size(); ++i) { ptr[i] = ref_data[i].data(); } return ptr; } template <typename T> inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) { std::vector<int> ret(data.size()); for (size_t i = 0; i < data.size(); ++i) { ret[i] = static_cast<int>(data[i].size()); } return ret; } inline static double AvoidInf(double x) { if (std::isnan(x)) { return 0.0; } else if (x >= 1e300) { return 1e300; } else if (x <= -1e300) { return -1e300; } else { return x; } } inline static float AvoidInf(float x) { if (std::isnan(x)) { return 0.0f; } else if (x >= 1e38) { return 1e38f; } else if (x <= -1e38) { return -1e38f; } else { return x; } } template<typename _Iter> inline static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) { return (0); } template<typename _RanIt, typename _Pr, typename _VTRanIt> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) { size_t len = _Last - _First; const size_t kMinInnerLen = 1024; int num_threads = OMP_NUM_THREADS(); if (len <= kMinInnerLen || num_threads <= 1) { std::sort(_First, _Last, _Pred); return; } size_t inner_size = (len + num_threads - 1) / num_threads; inner_size = std::max(inner_size, kMinInnerLen); num_threads = static_cast<int>((len + inner_size - 1) / inner_size); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < num_threads; ++i) { size_t left = inner_size*i; size_t right = left + inner_size; right = std::min(right, len); if (right > left) { std::sort(_First + left, _First + right, _Pred); } } // Buffer for merge. std::vector<_VTRanIt> temp_buf(len); _RanIt buf = temp_buf.begin(); size_t s = inner_size; // Recursive merge while (s < len) { int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2)); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < loop_size; ++i) { size_t left = i * 2 * s; size_t mid = left + s; size_t right = mid + s; right = std::min(len, right); if (mid >= right) { continue; } std::copy(_First + left, _First + mid, buf + left); std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred); } s *= 2; } } template<typename _RanIt, typename _Pr> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) { return ParallelSort(_First, _Last, _Pred, IteratorValType(_First)); } // Check that all y[] are in interval [ymin, ymax] (end points included); throws error if not template <typename T> inline static void CheckElementsIntervalClosed(const T *y, T ymin, T ymax, int ny, const char *callername) { auto fatal_msg = [&y, &ymin, &ymax, &callername](int i) { std::ostringstream os; os << "[%s]: does not tolerate element [#%i = " << y[i] << "] outside [" << ymin << ", " << ymax << "]"; Log::Fatal(os.str().c_str(), callername, i); }; for (int i = 1; i < ny; i += 2) { if (y[i - 1] < y[i]) { if (y[i - 1] < ymin) { fatal_msg(i - 1); } else if (y[i] > ymax) { fatal_msg(i); } } else { if (y[i - 1] > ymax) { fatal_msg(i - 1); } else if (y[i] < ymin) { fatal_msg(i); } } } if (ny & 1) { // odd if (y[ny - 1] < ymin || y[ny - 1] > ymax) { fatal_msg(ny - 1); } } } // One-pass scan over array w with nw elements: find min, max and sum of elements; // this is useful for checking weight requirements. template <typename T1, typename T2> inline static void ObtainMinMaxSum(const T1 *w, int nw, T1 *mi, T1 *ma, T2 *su) { T1 minw; T1 maxw; T1 sumw; int i; if (nw & 1) { // odd minw = w[0]; maxw = w[0]; sumw = w[0]; i = 2; } else { // even if (w[0] < w[1]) { minw = w[0]; maxw = w[1]; } else { minw = w[1]; maxw = w[0]; } sumw = w[0] + w[1]; i = 3; } for (; i < nw; i += 2) { if (w[i - 1] < w[i]) { minw = std::min(minw, w[i - 1]); maxw = std::max(maxw, w[i]); } else { minw = std::min(minw, w[i]); maxw = std::max(maxw, w[i - 1]); } sumw += w[i - 1] + w[i]; } if (mi != nullptr) { *mi = minw; } if (ma != nullptr) { *ma = maxw; } if (su != nullptr) { *su = static_cast<T2>(sumw); } } inline static std::vector<uint32_t> EmptyBitset(int n) { int size = n / 32; if (n % 32 != 0) ++size; return std::vector<uint32_t>(size); } template<typename T> inline static void InsertBitset(std::vector<uint32_t>* vec, const T val) { auto& ref_v = *vec; int i1 = val / 32; int i2 = val % 32; if (static_cast<int>(vec->size()) < i1 + 1) { vec->resize(i1 + 1, 0); } ref_v[i1] |= (1 << i2); } template<typename T> inline static std::vector<uint32_t> ConstructBitset(const T* vals, int n) { std::vector<uint32_t> ret; for (int i = 0; i < n; ++i) { int i1 = vals[i] / 32; int i2 = vals[i] % 32; if (static_cast<int>(ret.size()) < i1 + 1) { ret.resize(i1 + 1, 0); } ret[i1] |= (1 << i2); } return ret; } template<typename T> inline static bool FindInBitset(const uint32_t* bits, int n, T pos) { int i1 = pos / 32; if (i1 >= n) { return false; } int i2 = pos % 32; return (bits[i1] >> i2) & 1; } inline static bool CheckDoubleEqualOrdered(double a, double b) { double upper = std::nextafter(a, INFINITY); return b <= upper; } inline static double GetDoubleUpperBound(double a) { return std::nextafter(a, INFINITY); } inline static size_t GetLine(const char* str) { auto start = str; while (*str != '\0' && *str != '\n' && *str != '\r') { ++str; } return str - start; } inline static const char* SkipNewLine(const char* str) { if (*str == '\r') { ++str; } if (*str == '\n') { ++str; } return str; } template <typename T> static int Sign(T x) { return (x > T(0)) - (x < T(0)); } template <typename T> static T SafeLog(T x) { if (x > 0) { return std::log(x); } else { return -INFINITY; } } inline bool CheckAllowedJSON(const std::string& s) { unsigned char char_code; for (auto c : s) { char_code = static_cast<unsigned char>(c); if (char_code == 34 // " || char_code == 44 // , || char_code == 58 // : || char_code == 91 // [ || char_code == 93 // ] || char_code == 123 // { || char_code == 125 // } ) { return false; } } return true; } inline int RoundInt(double x) { return static_cast<int>(x + 0.5f); } template <typename T, std::size_t N = 32> class AlignmentAllocator { public: typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; inline AlignmentAllocator() throw() {} template <typename T2> inline AlignmentAllocator(const AlignmentAllocator<T2, N>&) throw() {} inline ~AlignmentAllocator() throw() {} inline pointer adress(reference r) { return &r; } inline const_pointer adress(const_reference r) const { return &r; } inline pointer allocate(size_type n) { return (pointer)_mm_malloc(n * sizeof(value_type), N); } inline void deallocate(pointer p, size_type) { _mm_free(p); } inline void construct(pointer p, const value_type& wert) { new (p) value_type(wert); } inline void destroy(pointer p) { p->~value_type(); } inline size_type max_size() const throw() { return size_type(-1) / sizeof(value_type); } template <typename T2> struct rebind { typedef AlignmentAllocator<T2, N> other; }; bool operator!=(const AlignmentAllocator<T, N>& other) const { return !(*this == other); } // Returns true if and only if storage allocated from *this // can be deallocated from other, and vice versa. // Always returns true for stateless allocators. bool operator==(const AlignmentAllocator<T, N>&) const { return true; } }; class Timer { public: Timer() { #ifdef TIMETAG int num_threads = OMP_NUM_THREADS(); start_time_.resize(num_threads); stats_.resize(num_threads); #endif // TIMETAG } ~Timer() { Print(); } #ifdef TIMETAG void Start(const std::string& name) { auto tid = omp_get_thread_num(); start_time_[tid][name] = std::chrono::steady_clock::now(); } void Stop(const std::string& name) { auto cur_time = std::chrono::steady_clock::now(); auto tid = omp_get_thread_num(); if (stats_[tid].find(name) == stats_[tid].end()) { stats_[tid][name] = std::chrono::duration<double, std::milli>(0); } stats_[tid][name] += cur_time - start_time_[tid][name]; } #else void Start(const std::string&) {} void Stop(const std::string&) {} #endif // TIMETAG void Print() const { #ifdef TIMETAG std::unordered_map<std::string, std::chrono::duration<double, std::milli>> stats(stats_[0].begin(), stats_[0].end()); for (size_t i = 1; i < stats_.size(); ++i) { for (auto it = stats_[i].begin(); it != stats_[i].end(); ++it) { if (stats.find(it->first) == stats.end()) { stats[it->first] = it->second; } else { stats[it->first] += it->second; } } } std::map<std::string, std::chrono::duration<double, std::milli>> ordered( stats.begin(), stats.end()); for (auto it = ordered.begin(); it != ordered.end(); ++it) { Log::Info("%s costs:\t %f", it->first.c_str(), it->second * 1e-3); } #endif // TIMETAG } #ifdef TIMETAG std::vector< std::unordered_map<std::string, std::chrono::steady_clock::time_point>> start_time_; std::vector<std::unordered_map<std::string, std::chrono::duration<double, std::milli>>> stats_; #endif // TIMETAG }; // Note: this class is not thread-safe, don't use it inside omp blocks class FunctionTimer { public: #ifdef TIMETAG FunctionTimer(const std::string& name, Timer& timer) : timer_(timer) { timer.Start(name); name_ = name; } ~FunctionTimer() { timer_.Stop(name_); } private: std::string name_; Timer& timer_; #else FunctionTimer(const std::string&, Timer&) {} #endif // TIMETAG }; } // namespace Common extern Common::Timer global_timer; } // namespace LightGBM #endif // LightGBM_UTILS_COMMON_FUN_H_
convolution_sgemm_pack4to8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void im2col_sgemm_pack4to8_avx(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { // Mat bottom_im2col(size, maxk, inch, 16u, 4, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; const float* bias = _bias; // permute Mat tmp; if (size >= 8) tmp.create(8 * maxk, inch, size / 8 + size % 8, 16u, 4, opt.workspace_allocator); else tmp.create(maxk, inch, size, 16u, 4, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = 0; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 8; float* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4; for (int k = 0; k < maxk; k++) { // transpose 4x8 __m128 _r0 = _mm_load_ps(img0); __m128 _r1 = _mm_load_ps(img0 + 4); __m128 _r2 = _mm_load_ps(img0 + 4 * 2); __m128 _r3 = _mm_load_ps(img0 + 4 * 3); __m128 _r4 = _mm_load_ps(img0 + 4 * 4); __m128 _r5 = _mm_load_ps(img0 + 4 * 5); __m128 _r6 = _mm_load_ps(img0 + 4 * 6); __m128 _r7 = _mm_load_ps(img0 + 4 * 7); _MM_TRANSPOSE4_PS(_r0, _r1, _r2, _r3); _MM_TRANSPOSE4_PS(_r4, _r5, _r6, _r7); _mm_store_ps(tmpptr, _r0); _mm_store_ps(tmpptr + 4, _r4); _mm_store_ps(tmpptr + 4 * 2, _r1); _mm_store_ps(tmpptr + 4 * 3, _r5); _mm_store_ps(tmpptr + 4 * 4, _r2); _mm_store_ps(tmpptr + 4 * 5, _r6); _mm_store_ps(tmpptr + 4 * 6, _r3); _mm_store_ps(tmpptr + 4 * 7, _r7); img0 += size * 4; tmpptr += 32; } } } remain_size_start += nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { float* tmpptr = tmp.channel(i / 8 + i % 8); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4; for (int k = 0; k < maxk; k++) { __m128 _val = _mm_load_ps(img0); _mm_store_ps(tmpptr, _val); img0 += size * 4; tmpptr += 4; } } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr0 = top_blob.channel(p); const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const float* biasptr = bias ? bias + p * 8 : zeros; int i = 0; for (; i + 7 < size; i += 8) { float* tmpptr = tmp.channel(i / 8); const float* kptr = kernel.channel(p); int nn = inch * maxk * 4; // inch always > 0 __m256 _sum0 = _mm256_loadu_ps(biasptr); __m256 _sum1 = _sum0; __m256 _sum2 = _sum0; __m256 _sum3 = _sum0; __m256 _sum4 = _sum0; __m256 _sum5 = _sum0; __m256 _sum6 = _sum0; __m256 _sum7 = _sum0; for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr); __m256 _val0 = _mm256_broadcast_ss(tmpptr); __m256 _val1 = _mm256_broadcast_ss(tmpptr + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1); __m256 _val2 = _mm256_broadcast_ss(tmpptr + 2); __m256 _val3 = _mm256_broadcast_ss(tmpptr + 3); _sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2); _sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3); __m256 _val4 = _mm256_broadcast_ss(tmpptr + 4); __m256 _val5 = _mm256_broadcast_ss(tmpptr + 5); _sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4); _sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5); __m256 _val6 = _mm256_broadcast_ss(tmpptr + 6); __m256 _val7 = _mm256_broadcast_ss(tmpptr + 7); _sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6); _sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7); kptr += 8; tmpptr += 8; } _mm256_store_ps(outptr0, _sum0); _mm256_store_ps(outptr0 + 8, _sum1); _mm256_store_ps(outptr0 + 8 * 2, _sum2); _mm256_store_ps(outptr0 + 8 * 3, _sum3); _mm256_store_ps(outptr0 + 8 * 4, _sum4); _mm256_store_ps(outptr0 + 8 * 5, _sum5); _mm256_store_ps(outptr0 + 8 * 6, _sum6); _mm256_store_ps(outptr0 + 8 * 7, _sum7); outptr0 += 8 * 8; } for (; i < size; i++) { float* tmpptr = tmp.channel(i / 8 + i % 8); const float* kptr = kernel.channel(p); int nn = inch * maxk * 4; // inch always > 0 __m256 _sum0 = _mm256_loadu_ps(biasptr); for (int j = 0; j < nn; j++) { __m256 _w0 = _mm256_load_ps(kptr); __m256 _val0 = _mm256_broadcast_ss(tmpptr); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); kptr += 8; tmpptr += 1; } _mm256_store_ps(outptr0, _sum0); outptr0 += 8; } } } static void convolution_im2col_sgemm_transform_kernel_pack4to8_avx(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = 8b-4a-maxk-inch/4a-outch/8b Mat kernel = _kernel.reshape(maxk, inch, outch); kernel_tm.create(32 * maxk, inch / 4, outch / 8, (size_t)4u); for (int q = 0; q + 7 < outch; q += 8) { float* g00 = kernel_tm.channel(q / 8); for (int p = 0; p + 3 < inch; p += 4) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 8; j++) { const float* k00 = kernel.channel(q + j).row(p + i); g00[0] = k00[k]; g00++; } } } } } } static void convolution_im2col_sgemm_pack4to8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 16u, 4, opt.workspace_allocator); { const int gap = (w * stride_h - outw * stride_w) * 4; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); float* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const float* sptr = img.row(dilation_h * u) + dilation_w * v * 4; for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m128 _val = _mm_load_ps(sptr); _mm_store_ps(ptr, _val); sptr += stride_w * 4; ptr += 4; } sptr += gap; } } } } } im2col_sgemm_pack4to8_avx(bottom_im2col, top_blob, kernel, _bias, opt); }
image-view.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % V V IIIII EEEEE W W % % V V I E W W % % V V I EEE W W W % % V V I E WW WW % % V IIIII EEEEE W W % % % % % % MagickCore Image View Methods % % % % Software Design % % Cristy % % March 2003 % % % % % % 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/MagickCore.h" #include "MagickCore/exception-private.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor-private.h" #include "MagickCore/thread-private.h" /* Typedef declarations. */ struct _ImageView { char *description; RectangleInfo extent; Image *image; CacheView *view; ExceptionInfo *exception; MagickBooleanType debug; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageView() makes a copy of the specified image view. % % The format of the CloneImageView method is: % % ImageView *CloneImageView(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport ImageView *CloneImageView(const ImageView *image_view) { ImageView *clone_view; assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); clone_view=(ImageView *) AcquireCriticalMemory(sizeof(*clone_view)); (void) ResetMagickMemory(clone_view,0,sizeof(*clone_view)); clone_view->description=ConstantString(image_view->description); clone_view->extent=image_view->extent; clone_view->view=CloneCacheView(image_view->view); clone_view->exception=AcquireExceptionInfo(); InheritException(clone_view->exception,image_view->exception); clone_view->debug=image_view->debug; clone_view->signature=MagickCoreSignature; return(clone_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageView() deallocates memory associated with a image view. % % The format of the DestroyImageView method is: % % ImageView *DestroyImageView(ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport ImageView *DestroyImageView(ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); if (image_view->description != (char *) NULL) image_view->description=DestroyString(image_view->description); image_view->view=DestroyCacheView(image_view->view); image_view->exception=DestroyExceptionInfo(image_view->exception); image_view->signature=(~MagickCoreSignature); image_view=(ImageView *) RelinquishMagickMemory(image_view); return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D u p l e x T r a n s f e r I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DuplexTransferImageViewIterator() iterates over three image views in % parallel and calls your transfer method for each scanline of the view. The % source and duplex pixel extent is not confined to the image canvas-- that is % you can include negative offsets or widths or heights that exceed the image % dimension. However, the destination image view is confined to the image % canvas-- that is no negative offsets or widths or heights that exceed the % image dimension are permitted. % % The callback signature is: % % MagickBooleanType DuplexTransferImageViewMethod(const ImageView *source, % const ImageView *duplex,ImageView *destination,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the DuplexTransferImageViewIterator method is: % % MagickBooleanType DuplexTransferImageViewIterator(ImageView *source, % ImageView *duplex,ImageView *destination, % DuplexTransferImageViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o duplex: the duplex image view. % % o destination: the destination image view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType DuplexTransferImageViewIterator( ImageView *source,ImageView *duplex,ImageView *destination, DuplexTransferImageViewMethod transfer,void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (transfer == (DuplexTransferImageViewMethod) NULL) return(MagickFalse); source_image=source->image; destination_image=destination->image; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict duplex_pixels, *magick_restrict pixels; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y, duplex->extent.width,1,duplex->exception); if (duplex_pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (transfer(source,duplex,destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_DuplexTransferImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewAuthenticMetacontent() returns the image view authentic % meta-content. % % The format of the GetImageViewAuthenticPixels method is: % % void *GetImageViewAuthenticMetacontent( % const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport void *GetImageViewAuthenticMetacontent( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewAuthenticMetacontent(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewAuthenticPixels() returns the image view authentic pixels. % % The format of the GetImageViewAuthenticPixels method is: % % Quantum *GetImageViewAuthenticPixels(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport Quantum *GetImageViewAuthenticPixels( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewAuthenticPixelQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewException() returns the severity, reason, and description of any % error that occurs when utilizing a image view. % % The format of the GetImageViewException method is: % % char *GetImageViewException(const PixelImage *image_view, % ExceptionType *severity) % % A description of each parameter follows: % % o image_view: the pixel image_view. % % o severity: the severity of the error is returned here. % */ MagickExport char *GetImageViewException(const ImageView *image_view, ExceptionType *severity) { char *description; assert(image_view != (const ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); assert(severity != (ExceptionType *) NULL); *severity=image_view->exception->severity; description=(char *) AcquireQuantumMemory(2UL*MagickPathExtent, sizeof(*description)); if (description == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *description='\0'; if (image_view->exception->reason != (char *) NULL) (void) CopyMagickString(description,GetLocaleExceptionMessage( image_view->exception->severity,image_view->exception->reason), MagickPathExtent); if (image_view->exception->description != (char *) NULL) { (void) ConcatenateMagickString(description," (",MagickPathExtent); (void) ConcatenateMagickString(description,GetLocaleExceptionMessage( image_view->exception->severity,image_view->exception->description), MagickPathExtent); (void) ConcatenateMagickString(description,")",MagickPathExtent); } return(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewExtent() returns the image view extent. % % The format of the GetImageViewExtent method is: % % RectangleInfo GetImageViewExtent(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport RectangleInfo GetImageViewExtent(const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(image_view->extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewImage() returns the image associated with the image view. % % The format of the GetImageViewImage method is: % % MagickCore *GetImageViewImage(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport Image *GetImageViewImage(const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(image_view->image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewIterator() iterates over the image view in parallel and calls % your get method for each scanline of the view. The pixel extent is % not confined to the image canvas-- that is you can include negative offsets % or widths or heights that exceed the image dimension. Any updates to % the pixels in your callback are ignored. % % The callback signature is: % % MagickBooleanType GetImageViewMethod(const ImageView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback get method that must be % executed by a single thread at a time. % % The format of the GetImageViewIterator method is: % % MagickBooleanType GetImageViewIterator(ImageView *source, % GetImageViewMethod get,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o get: the get callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType GetImageViewIterator(ImageView *source, GetImageViewMethod get,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (get == (GetImageViewMethod) NULL) return(MagickFalse); source_image=source->image; status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register const Quantum *pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } if (get(source,y,id,context) == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewVirtualMetacontent() returns the image view virtual % meta-content. % % The format of the GetImageViewVirtualMetacontent method is: % % const void *GetImageViewVirtualMetacontent( % const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport const void *GetImageViewVirtualMetacontent( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewVirtualMetacontent(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewVirtualPixels() returns the image view virtual pixels. % % The format of the GetImageViewVirtualPixels method is: % % const Quantum *GetImageViewVirtualPixels(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport const Quantum *GetImageViewVirtualPixels( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewVirtualPixelQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageView() returns MagickTrue if the the parameter is verified as a image % view object. % % The format of the IsImageView method is: % % MagickBooleanType IsImageView(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport MagickBooleanType IsImageView(const ImageView *image_view) { if (image_view == (const ImageView *) NULL) return(MagickFalse); if (image_view->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewImageView() returns a image view required for all other methods in the % Image View API. % % The format of the NewImageView method is: % % ImageView *NewImageView(MagickCore *wand,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageView *NewImageView(Image *image,ExceptionInfo *exception) { ImageView *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); image_view=(ImageView *) AcquireCriticalMemory(sizeof(*image_view)); (void) ResetMagickMemory(image_view,0,sizeof(*image_view)); image_view->description=ConstantString("ImageView"); image_view->image=image; image_view->view=AcquireVirtualCacheView(image_view->image,exception); image_view->extent.width=image->columns; image_view->extent.height=image->rows; image_view->extent.x=0; image_view->extent.y=0; image_view->exception=AcquireExceptionInfo(); image_view->debug=IsEventLogging(); image_view->signature=MagickCoreSignature; return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w I m a g e V i e w R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewImageViewRegion() returns a image view required for all other methods % in the Image View API. % % The format of the NewImageViewRegion method is: % % ImageView *NewImageViewRegion(MagickCore *wand,const ssize_t x, % const ssize_t y,const size_t width,const size_t height, % ExceptionInfo *exception) % % A description of each parameter follows: % % o wand: the magick wand. % % o x,y,columns,rows: These values define the perimeter of a extent of % pixel_wands view. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageView *NewImageViewRegion(Image *image,const ssize_t x, const ssize_t y,const size_t width,const size_t height, ExceptionInfo *exception) { ImageView *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); image_view=(ImageView *) AcquireCriticalMemory(sizeof(*image_view)); (void) ResetMagickMemory(image_view,0,sizeof(*image_view)); image_view->description=ConstantString("ImageView"); image_view->view=AcquireVirtualCacheView(image_view->image,exception); image_view->image=image; image_view->extent.width=width; image_view->extent.height=height; image_view->extent.x=x; image_view->extent.y=y; image_view->exception=AcquireExceptionInfo(); image_view->debug=IsEventLogging(); image_view->signature=MagickCoreSignature; return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w D e s c r i p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewDescription() associates a description with an image view. % % The format of the SetImageViewDescription method is: % % void SetImageViewDescription(ImageView *image_view, % const char *description) % % A description of each parameter follows: % % o image_view: the image view. % % o description: the image view description. % */ MagickExport void SetImageViewDescription(ImageView *image_view, const char *description) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); image_view->description=ConstantString(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewIterator() iterates over the image view in parallel and calls % your set method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension. The pixels are initiallly % undefined and any settings you make in the callback method are automagically % synced back to your image. % % The callback signature is: % % MagickBooleanType SetImageViewMethod(ImageView *destination, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback set method that must be % executed by a single thread at a time. % % The format of the SetImageViewIterator method is: % % MagickBooleanType SetImageViewIterator(ImageView *destination, % SetImageViewMethod set,void *context) % % A description of each parameter follows: % % o destination: the image view. % % o set: the set callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType SetImageViewIterator(ImageView *destination, SetImageViewMethod set,void *context) { Image *destination_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(destination != (ImageView *) NULL); assert(destination->signature == MagickCoreSignature); if (set == (SetImageViewMethod) NULL) return(MagickFalse); destination_image=destination->image; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=destination->extent.height-destination->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(destination_image,destination_image,height,1) #endif for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x, y,destination->extent.width,1,destination->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (set(destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (destination_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetImageViewIterator) #endif proceed=SetImageProgress(destination_image,destination->description, progress++,destination->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f e r I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransferImageViewIterator() iterates over two image views in parallel and % calls your transfer method for each scanline of the view. The source pixel % extent is not confined to the image canvas-- that is you can include % negative offsets or widths or heights that exceed the image dimension. % However, the destination image view is confined to the image canvas-- that % is no negative offsets or widths or heights that exceed the image dimension % are permitted. % % The callback signature is: % % MagickBooleanType TransferImageViewMethod(const ImageView *source, % ImageView *destination,const ssize_t y,const int thread_id, % void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the TransferImageViewIterator method is: % % MagickBooleanType TransferImageViewIterator(ImageView *source, % ImageView *destination,TransferImageViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o destination: the destination image view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType TransferImageViewIterator(ImageView *source, ImageView *destination,TransferImageViewMethod transfer,void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (transfer == (TransferImageViewMethod) NULL) return(MagickFalse); source_image=source->image; destination_image=destination->image; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict pixels; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (transfer(source,destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransferImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U p d a t e I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UpdateImageViewIterator() iterates over the image view in parallel and calls % your update method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension are permitted. Updates to pixels % in your callback are automagically synced back to the image. % % The callback signature is: % % MagickBooleanType UpdateImageViewMethod(ImageView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback update method that must be % executed by a single thread at a time. % % The format of the UpdateImageViewIterator method is: % % MagickBooleanType UpdateImageViewIterator(ImageView *source, % UpdateImageViewMethod update,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o update: the update callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType UpdateImageViewIterator(ImageView *source, UpdateImageViewMethod update,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (update == (UpdateImageViewMethod) NULL) return(MagickFalse); source_image=source->image; status=SetImageStorageClass(source_image,DirectClass,source->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (update(source,y,id,context) == MagickFalse) status=MagickFalse; status=SyncCacheViewAuthenticPixels(source->view,source->exception); if (status == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_UpdateImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); }
nco_rgr.c
/* $Header$ */ /* Purpose: NCO regridding utilities */ /* Copyright (C) 2015--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License with exceptions described in the LICENSE file */ #include "nco_rgr.h" /* Regridding */ extern double min_dbl(double a, double b); extern double max_dbl(double a, double b); inline double min_dbl(double a, double b){return (a < b) ? a : b;} inline double max_dbl(double a, double b){return (a > b) ? a : b;} int /* O [enm] Return code */ nco_rgr_ctl /* [fnc] Control regridding logic */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Control regridding logic */ int rcd=NCO_NOERR; const char fnc_nm[]="nco_rgr_ctl()"; nco_bool flg_grd=False; /* [flg] Create SCRIP-format grid file */ nco_bool flg_map=False; /* [flg] Create ESMF-format mapfile */ nco_bool flg_nfr=False; /* [flg] Infer SCRIP-format grid file */ nco_bool flg_smf=False; /* [flg] ESMF regridding (unused) */ nco_bool flg_s1d=False; /* [flg] Unpack sparse-1D CLM/ELM variables */ nco_bool flg_tps=False; /* [flg] Tempest regridding (unused) */ nco_bool flg_vrt=False; /* [flg] Interpolate to new vertical grid */ nco_bool flg_wgt=False; /* [flg] Regrid with external weights */ /* Main control branching occurs here Branching complexity and utility will increase as regridding features are added */ if(rgr->flg_grd) flg_grd=True; if(rgr->flg_grd_src && rgr->flg_grd_dst && rgr->flg_wgt) flg_map=True; if(rgr->flg_nfr) flg_nfr=True; if(rgr->flg_wgt && !(rgr->flg_grd_src && rgr->flg_grd_dst)) flg_wgt=True; if(rgr->flg_s1d) flg_s1d=True; if(rgr->fl_vrt) flg_vrt=True; assert(!flg_smf); assert(!flg_tps); /* Create SCRIP-format grid file */ if(flg_grd) rcd=nco_grd_mk(rgr); /* Create ESMF-format map file */ if(flg_map) rcd=nco_map_mk(rgr); /* Infer SCRIP-format grid file from data file */ if(flg_nfr) rcd=nco_grd_nfr(rgr); /* Interpolate data file to new vertical grid */ if(flg_vrt) rcd=nco_ntp_vrt(rgr,trv_tbl); /* Unpack sparse-1D CLM/ELM variables into full file */ if(flg_s1d) rcd=nco_s1d_unpack(rgr,trv_tbl); /* Regrid data horizontally using weights from mapping file */ if(flg_wgt) rcd=nco_rgr_wgt(rgr,trv_tbl); /* Regrid using ESMF library 20150701: On-line weight generation with ESMF never worked well and was abandoned */ if(flg_smf){ #ifdef ENABLE_ESMF (void)fprintf(stderr,"%s: %s calling nco_rgr_esmf() to generate and apply regridding map\n",nco_prg_nm_get(),fnc_nm); rcd=nco_rgr_esmf(rgr); /* Close output and free dynamic memory */ (void)nco_fl_out_cls(rgr->fl_out,rgr->fl_out_tmp,rgr->out_id); #else /* !ENABLE_ESMF */ (void)fprintf(stderr,"%s: ERROR %s reports attempt to use ESMF regridding without built-in support. Re-configure with --enable_esmf.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); #endif /* !ENABLE_ESMF */ } /* !flg_smf */ /* Regrid using TempestRemap regridding 20180314: Weight generation with Tempest is implemented off-line via ncremap, not internally on-line However, do not deprecate this since TempestRemap2 has a library that could be accessed on-line */ if(flg_tps) rcd=nco_rgr_tps(rgr); return rcd; } /* end nco_rgr_ctl() */ rgr_sct * /* O [sct] Pointer to free'd regridding structure */ nco_rgr_free /* [fnc] Deallocate regridding structure */ (rgr_sct *rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Free all dynamic memory in regridding structure */ /* free() standalone command-line arguments */ if(rgr->cmd_ln) rgr->cmd_ln=(char *)nco_free(rgr->cmd_ln); if(rgr->grd_ttl) rgr->grd_ttl=(char *)nco_free(rgr->grd_ttl); if(rgr->fl_grd_src) rgr->fl_grd_src=(char *)nco_free(rgr->fl_grd_src); if(rgr->fl_grd_dst) rgr->fl_grd_dst=(char *)nco_free(rgr->fl_grd_dst); if(rgr->fl_hrz) rgr->fl_hrz=(char *)nco_free(rgr->fl_hrz); if(rgr->fl_in) rgr->fl_in=(char *)nco_free(rgr->fl_in); if(rgr->fl_map) rgr->fl_map=(char *)nco_free(rgr->fl_map); if(rgr->fl_msh) rgr->fl_msh=(char *)nco_free(rgr->fl_msh); if(rgr->fl_out) rgr->fl_out=(char *)nco_free(rgr->fl_out); if(rgr->fl_out_tmp) rgr->fl_out_tmp=(char *)nco_free(rgr->fl_out_tmp); if(rgr->fl_vrt) rgr->fl_vrt=(char *)nco_free(rgr->fl_vrt); if(rgr->var_nm) rgr->var_nm=(char *)nco_free(rgr->var_nm); if(rgr->xtn_var) rgr->xtn_var=(char **)nco_sng_lst_free(rgr->xtn_var,rgr->xtn_nbr); /* free() strings associated with grid properties */ if(rgr->fl_grd) rgr->fl_grd=(char *)nco_free(rgr->fl_grd); if(rgr->fl_hnt_dst) rgr->fl_hnt_dst=(char *)nco_free(rgr->fl_hnt_dst); if(rgr->fl_hnt_src) rgr->fl_hnt_src=(char *)nco_free(rgr->fl_hnt_src); if(rgr->fl_skl) rgr->fl_skl=(char *)nco_free(rgr->fl_skl); if(rgr->fl_ugrid) rgr->fl_ugrid=(char *)nco_free(rgr->fl_ugrid); /* Tempest */ if(rgr->drc_tps) rgr->drc_tps=(char *)nco_free(rgr->drc_tps); /* free() memory used to construct KVMs */ if(rgr->rgr_nbr > 0) rgr->rgr_arg=nco_sng_lst_free(rgr->rgr_arg,rgr->rgr_nbr); /* free() memory copied from KVMs */ if(rgr->area_nm) rgr->area_nm=(char *)nco_free(rgr->area_nm); if(rgr->bnd_nm) rgr->bnd_nm=(char *)nco_free(rgr->bnd_nm); if(rgr->bnd_tm_nm) rgr->bnd_tm_nm=(char *)nco_free(rgr->bnd_tm_nm); if(rgr->col_nm_in) rgr->col_nm_in=(char *)nco_free(rgr->col_nm_in); if(rgr->col_nm_out) rgr->col_nm_out=(char *)nco_free(rgr->col_nm_out); if(rgr->frc_nm) rgr->frc_nm=(char *)nco_free(rgr->frc_nm); if(rgr->ilev_nm_in) rgr->ilev_nm_in=(char *)nco_free(rgr->ilev_nm_in); if(rgr->ilev_nm_out) rgr->ilev_nm_out=(char *)nco_free(rgr->ilev_nm_out); if(rgr->lat_bnd_nm) rgr->lat_bnd_nm=(char *)nco_free(rgr->lat_bnd_nm); if(rgr->lat_nm_in) rgr->lat_nm_in=(char *)nco_free(rgr->lat_nm_in); if(rgr->lat_nm_out) rgr->lat_nm_out=(char *)nco_free(rgr->lat_nm_out); if(rgr->lat_vrt_nm) rgr->lat_vrt_nm=(char *)nco_free(rgr->lat_vrt_nm); if(rgr->lat_wgt_nm) rgr->lat_wgt_nm=(char *)nco_free(rgr->lat_wgt_nm); if(rgr->lev_nm_in) rgr->lev_nm_in=(char *)nco_free(rgr->lev_nm_in); if(rgr->lev_nm_out) rgr->lev_nm_out=(char *)nco_free(rgr->lev_nm_out); if(rgr->lon_bnd_nm) rgr->lon_bnd_nm=(char *)nco_free(rgr->lon_bnd_nm); if(rgr->lon_nm_in) rgr->lon_nm_in=(char *)nco_free(rgr->lon_nm_in); if(rgr->lon_nm_out) rgr->lon_nm_out=(char *)nco_free(rgr->lon_nm_out); if(rgr->lon_vrt_nm) rgr->lon_vrt_nm=(char *)nco_free(rgr->lon_vrt_nm); if(rgr->msk_nm) rgr->msk_nm=(char *)nco_free(rgr->msk_nm); if(rgr->plev_nm_in) rgr->plev_nm_in=(char *)nco_free(rgr->plev_nm_in); if(rgr->vrt_nm) rgr->vrt_nm=(char *)nco_free(rgr->vrt_nm); /* Lastly, free() regrid structure itself */ if(rgr) rgr=(rgr_sct *)nco_free(rgr); return rgr; } /* end nco_rgr_free() */ rgr_sct * /* O [sct] Regridding structure */ nco_rgr_ini /* [fnc] Initialize regridding structure */ (const char * const cmd_ln, /* I [sng] Command-line */ const int in_id, /* I [id] Input netCDF file ID */ char **rgr_arg, /* [sng] Regridding arguments */ const int rgr_arg_nbr, /* [nbr] Number of regridding arguments */ char * const rgr_in, /* I [sng] File containing fields to be regridded */ char * const rgr_out, /* I [sng] File containing regridded fields */ char * const rgr_grd_src, /* I [sng] File containing input grid */ char * const rgr_grd_dst, /* I [sng] File containing destination grid */ char * const rgr_hrz, /* I [sng] File containing horizontal coordinate grid */ char * const rgr_map, /* I [sng] File containing mapping weights from source to destination grid */ char * const rgr_var, /* I [sng] Variable for special regridding treatment */ char * const rgr_vrt, /* I [sng] File containing vertical coordinate grid */ const double wgt_vld_thr, /* I [frc] Weight threshold for valid destination value */ char **xtn_var, /* [sng] I Extensive variables */ const int xtn_nbr) /* [nbr] I Number of extensive variables */ { /* Purpose: Initialize regridding structure */ const char fnc_nm[]="nco_rgr_ini()"; rgr_sct *rgr; /* Allocate */ rgr=(rgr_sct *)nco_malloc(sizeof(rgr_sct)); /* Initialize variables directly or indirectly set via command-line (except for key-value arguments) */ rgr->cmd_ln=strdup(cmd_ln); /* [sng] Command-line */ rgr->flg_usr_rqs=False; /* [flg] User requested regridding */ rgr->out_id=int_CEWI; /* [id] Output netCDF file ID */ rgr->in_id=in_id; /* [id] Input netCDF file ID */ rgr->rgr_arg=rgr_arg; /* [sng] Regridding arguments */ rgr->rgr_nbr=rgr_arg_nbr; /* [nbr] Number of regridding arguments */ rgr->drc_tps=NULL; /* [sng] Directory where Tempest grids, meshes, and weights are stored */ rgr->flg_grd_src= rgr_grd_src ? True : False; /* [flg] User-specified input grid */ rgr->fl_grd_src=rgr_grd_src; /* [sng] File containing input grid */ rgr->flg_grd_dst= rgr_grd_dst ? True : False; /* [flg] User-specified destination grid */ rgr->fl_grd_dst=rgr_grd_dst; /* [sng] File containing destination grid */ rgr->fl_in=rgr_in; /* [sng] File containing fields to be regridded */ rgr->fl_out=rgr_out; /* [sng] File containing regridded fields */ rgr->fl_out_tmp=NULL_CEWI; /* [sng] Temporary file containing regridded fields */ rgr->flg_wgt= rgr_map ? True : False; /* [flg] User-specified mapping weights */ rgr->fl_map=rgr_map; /* [sng] File containing mapping weights from source to destination grid */ rgr->fl_hrz=rgr_hrz; /* [sng] [sng] File containing horizontal coordinate grid (for S1D) */ rgr->fl_vrt=rgr_vrt; /* [sng] [sng] File containing vertical coordinate grid */ rgr->var_nm=rgr_var; /* [sng] Variable for special regridding treatment */ rgr->xtn_var=xtn_var; /* [sng] Extensive variables */ rgr->xtn_nbr=xtn_nbr; /* [nbr] Number of extensive variables */ /* Did user explicitly request regridding? */ if(rgr_arg_nbr > 0 || rgr_grd_src != NULL || rgr_grd_dst != NULL || rgr_map != NULL || rgr_vrt != NULL) rgr->flg_usr_rqs=True; /* Initialize arguments after copying */ if(!rgr->fl_out) rgr->fl_out=(char *)strdup("/data/zender/rgr/rgr_out.nc"); if(!rgr->fl_grd_dst) rgr->fl_grd_dst=(char *)strdup("/data/zender/scrip/grids/remap_grid_T42.nc"); // if(!rgr->var_nm) rgr->var_nm=(char *)strdup("ORO"); if(nco_dbg_lvl_get() >= nco_dbg_crr){ (void)fprintf(stderr,"%s: INFO %s reports ",nco_prg_nm_get(),fnc_nm); (void)fprintf(stderr,"flg_usr_rqs = %d, ",rgr->flg_usr_rqs); (void)fprintf(stderr,"rgr_nbr = %d, ",rgr->rgr_nbr); (void)fprintf(stderr,"fl_grd_src = %s, ",rgr->fl_grd_src ? rgr->fl_grd_src : "NULL"); (void)fprintf(stderr,"fl_grd_dst = %s, ",rgr->fl_grd_dst ? rgr->fl_grd_dst : "NULL"); (void)fprintf(stderr,"fl_hrz = %s, ",rgr->fl_hrz ? rgr->fl_hrz : "NULL"); (void)fprintf(stderr,"fl_in = %s, ",rgr->fl_in ? rgr->fl_in : "NULL"); (void)fprintf(stderr,"fl_out = %s, ",rgr->fl_out ? rgr->fl_out : "NULL"); (void)fprintf(stderr,"fl_out_tmp = %s, ",rgr->fl_out_tmp ? rgr->fl_out_tmp : "NULL"); (void)fprintf(stderr,"fl_map = %s, ",rgr->fl_map ? rgr->fl_map : "NULL"); (void)fprintf(stderr,"fl_vrt = %s, ",rgr->fl_vrt ? rgr->fl_vrt : "NULL"); (void)fprintf(stderr,"\n"); } /* endif dbg */ /* Flags */ if(wgt_vld_thr == NC_MIN_DOUBLE){ rgr->flg_rnr=False; }else if(wgt_vld_thr >= 0.0 && wgt_vld_thr <= 1.0){ /* NB: Weight thresholds of 0.0 or nearly zero can lead to underflow or divide-by-zero errors */ // const double wgt_vld_thr_min=1.0e-10; /* [frc] Minimum weight threshold for valid destination value */ rgr->flg_rnr=True; rgr->wgt_vld_thr=wgt_vld_thr; }else{ (void)fprintf(stderr,"%s: ERROR weight threshold must be in [0.0,1.0] and user supplied wgt_vld_thr = %g\n",nco_prg_nm_get(),wgt_vld_thr); nco_exit(EXIT_FAILURE); } /* endif */ /* Parse extended kvm options */ char *sng_fnl=NULL; int cnv_nbr; /* [nbr] Number of elements converted by sscanf() */ int rgr_var_idx; /* [idx] Index over rgr_lst (i.e., all names explicitly specified in all "--rgr var1[,var2]=val" options) */ int rgr_var_nbr=0; kvm_sct *rgr_lst=NULL; /* [sct] List of all regrid specifications */ if(rgr_arg_nbr > 0){ /* Join arguments together */ sng_fnl=nco_join_sng(rgr_arg,rgr_arg_nbr); rgr_lst=nco_arg_mlt_prs(sng_fnl); if(sng_fnl) sng_fnl=(char *)nco_free(sng_fnl); /* Count number of keys */ for(rgr_var_idx=0;(rgr_lst+rgr_var_idx)->key;rgr_var_idx++,rgr_var_nbr++);/* !rgr_var_idx */ } /* !rgr_arg_nbr */ /* NULL-initialize key-value properties required for string variables */ rgr->area_nm=NULL; /* [sng] Name of variable containing gridcell area */ rgr->bnd_nm=NULL; /* [sng] Name of dimension to employ for spatial bounds */ rgr->bnd_tm_nm=NULL; /* [sng] Name of dimension to employ for temporal bounds */ rgr->col_nm_in=NULL; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ rgr->col_nm_out=NULL; /* [sng] Name of horizontal spatial output dimension on unstructured grid */ rgr->frc_nm=NULL; /* [sng] Name of variable containing gridcell fraction */ rgr->ilev_nm_in=NULL; /* [sng] Name of input dimension to recognize as vertical dimension at layer interfaces */ rgr->ilev_nm_out=NULL; /* [sng] Name of output vertical dimension at layer interfaces */ rgr->lat_bnd_nm=NULL; /* [sng] Name of rectangular boundary variable for latitude */ rgr->lat_dmn_nm=NULL; /* [sng] Name of latitude dimension in inferred grid */ rgr->lat_nm_in=NULL; /* [sng] Name of input dimension to recognize as latitude */ rgr->lat_nm_out=NULL; /* [sng] Name of output dimension for latitude */ rgr->lat_vrt_nm=NULL; /* [sng] Name of non-rectangular boundary variable for latitude */ rgr->lat_wgt_nm=NULL; /* [sng] Name of variable containing latitude weights */ rgr->lev_nm_in=NULL; /* [sng] Name of input dimension to recognize as vertical dimension at layer midpoints */ rgr->lev_nm_out=NULL; /* [sng] Name of output vertical dimension at layer midpoints */ rgr->lon_bnd_nm=NULL; /* [sng] Name of rectangular boundary variable for longitude */ rgr->lon_dmn_nm=NULL; /* [sng] Name of longitude dimension in inferred grid */ rgr->lon_nm_in=NULL; /* [sng] Name of dimension to recognize as longitude */ rgr->lon_nm_out=NULL; /* [sng] Name of output dimension for longitude */ rgr->lon_vrt_nm=NULL; /* [sng] Name of non-rectangular boundary variable for longitude */ rgr->msk_nm=NULL; /* [sng] Name of variable containing destination mask */ rgr->plev_nm_in=NULL; /* [sng] Name of input variable recognize as pure-pressure coordinate */ rgr->sgs_frc_nm=NULL; /* [sng] Name of variable sub-gridscale fraction */ rgr->sgs_msk_nm=NULL; /* [sng] Name of variable sub-gridscale mask */ rgr->vrt_nm=NULL; /* [sng] Name of dimension to employ for vertices */ /* Initialize key-value properties used in grid and weight generation */ rgr->area_mth=1; /* [enm] Method to compute grid cell area */ rgr->edg_typ=nco_edg_nil; /* [enm] Edge/Arc-type for triangle edges */ rgr->fl_grd=NULL; /* [sng] Name of SCRIP grid file to create */ rgr->fl_hnt_dst=NULL; /* [sng] ERWG hint destination */ rgr->fl_hnt_src=NULL; /* [sng] ERWG hint source */ rgr->fl_msh=NULL; /* [sng] Name of SCRIP intersection mesh file to create */ rgr->fl_skl=NULL; /* [sng] Name of skeleton data file to create */ rgr->fl_ugrid=NULL; /* [sng] Name of UGRID grid file to create */ rgr->flg_add_fll=False; /* [flg] Add _FillValue to fields with empty destination cells */ rgr->flg_area_out=True; /* [flg] Add area to output */ rgr->flg_cf_units=False; /* [flg] Generate CF-compliant (breaks ERWG 7.1.0r-) units fields in SCRIP-format grid files */ rgr->flg_cll_msr=True; /* [flg] Add cell_measures attribute */ rgr->flg_crv=False; /* [flg] Use curvilinear coordinates */ rgr->flg_dgn_area=False; /* [flg] Diagnose rather than copy inferred area */ rgr->flg_dgn_bnd=False; /* [flg] Diagnose rather than copy inferred bounds */ rgr->flg_erwg_units=True; /* [flg] Generate ERWG 7.1.0r-compliant SCRIP-format grid files */ rgr->flg_grd=False; /* [flg] Create SCRIP-format grid file */ rgr->flg_msk_apl=False; /* [flg] Apply msk_out to variables after regridding */ rgr->flg_msk_out=False; /* [flg] Add mask to output */ rgr->flg_nfr=False; /* [flg] Infer SCRIP-format grid file */ rgr->flg_s1d=False; /* [flg] Unpack sparse-1D CLM/ELM variables */ rgr->flg_stg=True; /* [flg] Write staggered grid with FV output */ rgr->grd_ttl=strdup("None given (supply with --rgr grd_ttl=\"Grid Title\")"); /* [enm] Grid title */ rgr->grd_typ=nco_grd_2D_eqa; /* [enm] Grid type */ rgr->idx_dbg=0; /* [idx] Index of gridcell for debugging */ rgr->lat_drc=nco_grd_lat_drc_s2n; /* [enm] Latitude grid direction */ rgr->lat_typ=nco_grd_lat_eqa; /* [enm] Latitude grid type */ rgr->lon_typ=nco_grd_lon_Grn_ctr; /* [enm] Longitude grid type */ rgr->lat_nbr=180; /* [nbr] Number of latitudes in destination grid */ rgr->lon_nbr=360; /* [nbr] Number of longitudes in destination grid */ rgr->lat_crv=0.0; /* [dgr] Latitudinal curvilinearity */ rgr->lon_crv=0.0; /* [dgr] Longitudinal curvilinearity */ rgr->lat_sth=NC_MAX_DOUBLE; /* [dgr] Latitude of southern edge of grid */ rgr->lon_wst=NC_MAX_DOUBLE; /* [dgr] Longitude of western edge of grid */ rgr->lat_nrt=NC_MAX_DOUBLE; /* [dgr] Latitude of northern edge of grid */ rgr->lon_est=NC_MAX_DOUBLE; /* [dgr] Longitude of eastern edge of grid */ rgr->msk_var=NULL; /* [sng] Mask-template variable */ rgr->ply_tri_mth=nco_ply_tri_mth_csz; /* [enm] Polygon-to-triangle decomposition method */ rgr->sgs_nrm=1.0; /* [sng] Sub-gridscale normalization */ rgr->tst=0L; /* [enm] Generic key for testing (undocumented) */ rgr->ntp_mth=nco_ntp_log; /* [enm] Interpolation method */ rgr->xtr_mth=nco_xtr_fll_ngh; /* [enm] Extrapolation method */ rgr->xtr_nsp=8; /* [sng] Extrapolation number of source points */ rgr->xtr_xpn=2.0; /* [sng] Exponent of distance in extrapolation (absolute value) */ rgr->wgt_typ=nco_wgt_con; /* [enm] Weight generation method */ /* Parse key-value properties */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ for(rgr_var_idx=0;rgr_var_idx<rgr_var_nbr;rgr_var_idx++){ if(!strcmp(rgr_lst[rgr_var_idx].key,"grid") || !strcasecmp(rgr_lst[rgr_var_idx].key,"scrip")){ rgr->fl_grd=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_grd=True; continue; } /* !grid */ if(!strcmp(rgr_lst[rgr_var_idx].key,"hnt_dst") || !strcmp(rgr_lst[rgr_var_idx].key,"fl_hnt_dst")){ rgr->fl_hnt_dst=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !hnt_dst */ if(!strcmp(rgr_lst[rgr_var_idx].key,"hnt_src") || !strcmp(rgr_lst[rgr_var_idx].key,"fl_hnt_src")){ rgr->fl_hnt_src=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !hnt_src */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_var") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_var") || !strcmp(rgr_lst[rgr_var_idx].key,"mask") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_variable")){ rgr->msk_var=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_msk_out=True; continue; } /* !msk_var */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msh") || !strcmp(rgr_lst[rgr_var_idx].key,"mesh")){ rgr->fl_msh=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !msh */ if(!strcmp(rgr_lst[rgr_var_idx].key,"skl")){ rgr->fl_skl=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_grd=True; continue; } /* !skl */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"ugrid")){ rgr->fl_ugrid=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_nfr=True; continue; } /* !ugrid */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"fl_hrz") || !strcasecmp(rgr_lst[rgr_var_idx].key,"hrz")){ rgr->fl_hrz=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !hrz */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"fl_vrt") || !strcasecmp(rgr_lst[rgr_var_idx].key,"vrt")){ rgr->fl_vrt=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !vrt */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_area") || !strcmp(rgr_lst[rgr_var_idx].key,"no_area_out")){ rgr->flg_area_out=False; continue; } /* !area */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_msk") || !strcmp(rgr_lst[rgr_var_idx].key,"no_msk_out") || !strcmp(rgr_lst[rgr_var_idx].key,"no_mask") || !strcmp(rgr_lst[rgr_var_idx].key,"no_mask_out")){ rgr->flg_msk_out=False; continue; } /* !msk */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_apl") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_apply")){ rgr->flg_msk_apl=True; /* Ensure masked fields regridded with TR maps have _FillValue to guarantee BFB arithmetic with masked fields regridded with other maps that adhere to SCRIP/ESMF mask rules */ rgr->flg_add_fll=True; continue; } /* !msk_apl */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_out") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_out")){ rgr->flg_msk_out=True; continue; } /* !mask */ if(!strcmp(rgr_lst[rgr_var_idx].key,"add_fll") || !strcmp(rgr_lst[rgr_var_idx].key,"add_fill_value") || !strcmp(rgr_lst[rgr_var_idx].key,"fll_mpt") || !strcmp(rgr_lst[rgr_var_idx].key,"fill_empty")){ rgr->flg_add_fll=True; continue; } /* !add_fll */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cell_measures") || !strcmp(rgr_lst[rgr_var_idx].key,"cll_msr")){ rgr->flg_cll_msr=True; continue; } /* !cell_measures */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_cell_measures") || !strcmp(rgr_lst[rgr_var_idx].key,"no_cll_msr")){ rgr->flg_cll_msr=False; continue; } /* !cell_measures */ if(!strcmp(rgr_lst[rgr_var_idx].key,"curvilinear") || !strcmp(rgr_lst[rgr_var_idx].key,"crv")){ rgr->flg_crv=True; continue; } /* !curvilinear */ if(!strcmp(rgr_lst[rgr_var_idx].key,"diagnose_area") || !strcmp(rgr_lst[rgr_var_idx].key,"dgn_area") || !strcmp(rgr_lst[rgr_var_idx].key,"area_diagnose") || !strcmp(rgr_lst[rgr_var_idx].key,"area_dgn")){ rgr->flg_dgn_area=True; continue; } /* !diagnose_area */ if(!strcmp(rgr_lst[rgr_var_idx].key,"diagnose_bounds") || !strcmp(rgr_lst[rgr_var_idx].key,"dgn_bnd")){ rgr->flg_dgn_bnd=True; continue; } /* !diagnose_bounds */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cf_units") || !strcmp(rgr_lst[rgr_var_idx].key,"CF_units")){ rgr->flg_cf_units=True; rgr->flg_erwg_units=False; continue; } /* !erwg_units */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cell_area_quad")){ rgr->area_mth=2; continue; } /* !area_nco */ if(!strcmp(rgr_lst[rgr_var_idx].key,"cell_area_nco")){ rgr->area_mth=1; continue; } /* !area_nco */ if(!strcmp(rgr_lst[rgr_var_idx].key,"edg_typ") || !strcmp(rgr_lst[rgr_var_idx].key,"tri_arc") || !strcmp(rgr_lst[rgr_var_idx].key,"vrt_cnc")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"grt_crc") || !strcasecmp(rgr_lst[rgr_var_idx].val,"gtc") || !strcasecmp(rgr_lst[rgr_var_idx].val,"great_circle") || !strcasecmp(rgr_lst[rgr_var_idx].val,"geodesic") || !strcasecmp(rgr_lst[rgr_var_idx].val,"orthodrome")){ rgr->edg_typ=nco_edg_gtc; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"sml_crc") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ltr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"small_circle") || !strcasecmp(rgr_lst[rgr_var_idx].val,"latitude_triangle") || !strcasecmp(rgr_lst[rgr_var_idx].val,"true")){ rgr->edg_typ=nco_edg_smc; (void)fprintf(stderr,"%s: WARNING Requested to run with small-circle edges. This option has not yet been tested and validated. Use only at your own risk.\n",nco_prg_nm_get()); }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"crt") || !strcasecmp(rgr_lst[rgr_var_idx].val,"cartesian") || !strcasecmp(rgr_lst[rgr_var_idx].val,"planar") || !strcasecmp(rgr_lst[rgr_var_idx].val,"flat")){ rgr->edg_typ=nco_edg_crt; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !edg_typ */ if(!strcmp(rgr_lst[rgr_var_idx].key,"erwg_units") || !strcmp(rgr_lst[rgr_var_idx].key,"esmf_units") || !strcmp(rgr_lst[rgr_var_idx].key,"degrees")){ rgr->flg_cf_units=False; rgr->flg_erwg_units=True; continue; } /* !erwg_units */ if(!strcmp(rgr_lst[rgr_var_idx].key,"infer") || !strcmp(rgr_lst[rgr_var_idx].key,"nfr")){ rgr->flg_nfr=True; continue; } /* !infer */ if(!strcmp(rgr_lst[rgr_var_idx].key,"no_stagger") || !strcmp(rgr_lst[rgr_var_idx].key,"no_stg")){ rgr->flg_stg=False; continue; } /* !stagger */ if(!strcmp(rgr_lst[rgr_var_idx].key,"grd_ttl") || !strcmp(rgr_lst[rgr_var_idx].key,"ttl")){ if(rgr->grd_ttl) rgr->grd_ttl=(char *)nco_free(rgr->grd_ttl); rgr->grd_ttl=(char *)strdup(rgr_lst[rgr_var_idx].val); /* 20180828 Replace unquoted tildes with spaces (like LaTeX, NCL) so ncremap users can put tildes in place of spaces in ttl 20180905 Reverted this since quoting command in ncremap is superior solution */ if(False){ size_t ttl_lng=strlen(rgr->grd_ttl); for(size_t ttl_idx=0L;ttl_idx<ttl_lng;ttl_idx++) if(rgr->grd_ttl[ttl_idx] == '~'){ if(ttl_idx == 0L) rgr->grd_ttl[ttl_idx]=' '; // Always convert tilde to space if first character else if(rgr->grd_ttl[ttl_idx-1L] != '\\') rgr->grd_ttl[ttl_idx]=' '; // Convert tilde in other locations unless backslash-quoted } /* !tilde */ } /* !0 */ continue; } /* !grd_ttl */ if(!strcmp(rgr_lst[rgr_var_idx].key,"idx_dbg")){ rgr->idx_dbg=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !idx_dbg */ if(!strcmp(rgr_lst[rgr_var_idx].key,"latlon")){ cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%ld,%ld",&rgr->lat_nbr,&rgr->lon_nbr); assert(cnv_nbr == 2); continue; } /* !latlon */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lonlat")){ cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%ld,%ld",&rgr->lon_nbr,&rgr->lat_nbr); assert(cnv_nbr == 2); continue; } /* !lonlat */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nbr")){ rgr->lat_nbr=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !lat_nbr */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_nbr")){ rgr->lon_nbr=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !lon_nbr */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"snwe")){ cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%lf,%lf,%lf,%lf",&rgr->lat_sth,&rgr->lat_nrt,&rgr->lon_wst,&rgr->lon_est); if(cnv_nbr != 4) (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); assert(cnv_nbr == 4); if(cnv_nbr != 4) abort(); /* CEWI Use cnv_nbr at least once outside of assert() to avoid gcc 4.8.2 set-but-not-used warning */ continue; } /* !snwe */ if(!strcasecmp(rgr_lst[rgr_var_idx].key,"wesn")){ if(cnv_nbr != 4) cnv_nbr=sscanf(rgr_lst[rgr_var_idx].val,"%lf,%lf,%lf,%lf",&rgr->lon_wst,&rgr->lon_est,&rgr->lat_sth,&rgr->lat_nrt); assert(cnv_nbr == 4); continue; } /* !wesn */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_crv")){ rgr->lat_crv=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !lat_crv */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_crv")){ rgr->lon_crv=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !lon_crv */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_sth")){ rgr->lat_sth=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); // rgr->lat_typ=nco_grd_lat_bb; continue; } /* !lat_sth */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_wst")){ rgr->lon_wst=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); rgr->lon_typ=nco_grd_lon_bb; continue; } /* !lon_wst */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nrt")){ rgr->lat_nrt=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); //rgr->lat_typ=nco_grd_lat_bb; continue; } /* !lat_nrt */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_est")){ rgr->lon_est=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); rgr->lon_typ=nco_grd_lon_bb; continue; } /* !lon_est */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_drc")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"s2n") || !strcasecmp(rgr_lst[rgr_var_idx].val,"south2north") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ston") || !strcasecmp(rgr_lst[rgr_var_idx].val,"southnorth")){ rgr->lat_drc=nco_grd_lat_drc_s2n; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"n2s") || !strcasecmp(rgr_lst[rgr_var_idx].val,"north2south") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ntos") || !strcasecmp(rgr_lst[rgr_var_idx].val,"northsouth")){ rgr->lat_drc=nco_grd_lat_drc_n2s; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !lat_drc */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_typ")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"cap") || !strcasecmp(rgr_lst[rgr_var_idx].val,"fv") || !strcasecmp(rgr_lst[rgr_var_idx].val,"fix") || !strcasecmp(rgr_lst[rgr_var_idx].val,"yarmulke")){ rgr->lat_typ=nco_grd_lat_fv; rgr->grd_typ=nco_grd_2D_fv; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"eqa") || !strcasecmp(rgr_lst[rgr_var_idx].val,"rgl") || !strcasecmp(rgr_lst[rgr_var_idx].val,"unf") || !strcasecmp(rgr_lst[rgr_var_idx].val,"uni")){ rgr->lat_typ=nco_grd_lat_eqa; rgr->grd_typ=nco_grd_2D_eqa; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"gss")){ rgr->lat_typ=nco_grd_lat_gss; rgr->grd_typ=nco_grd_2D_gss; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !lat_typ */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_typ")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"180_wst") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wst_180")) rgr->lon_typ=nco_grd_lon_180_wst; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"180_ctr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ctr_180")) rgr->lon_typ=nco_grd_lon_180_ctr; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"Grn_wst") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wst_Grn")) rgr->lon_typ=nco_grd_lon_Grn_wst; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"Grn_ctr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ctr_Grn")) rgr->lon_typ=nco_grd_lon_Grn_ctr; else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !lon_typ */ if(!strcmp(rgr_lst[rgr_var_idx].key,"area_nm")){ rgr->area_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !area_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"bnd_nm")){ rgr->bnd_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !bnd_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"bnd_tm_nm")){ rgr->bnd_tm_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !bnd_tm_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"col_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"col_nm")){ rgr->col_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !col_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"col_nm_out")){ rgr->col_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !col_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"frc_nm")){ rgr->frc_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !frc_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"ilev_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"ilev_nm")){ rgr->ilev_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !ilev_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"ilev_nm_out")){ rgr->ilev_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !ilev_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_bnd_nm")){ rgr->lat_bnd_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_bnd_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_dmn_nm") || !strcmp(rgr_lst[rgr_var_idx].key,"lat_dmn")){ rgr->lat_dmn_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_dmn_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"lat_nm")){ rgr->lat_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_nm_out")){ rgr->lat_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_vrt_nm")){ rgr->lat_vrt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_vrt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lat_wgt_nm")){ rgr->lat_wgt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lat_wgt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lev_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"lev_nm")){ rgr->lev_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lev_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lev_nm_out")){ rgr->lev_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lev_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_bnd_nm")){ rgr->lon_bnd_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_bnd_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_dmn_nm") || !strcmp(rgr_lst[rgr_var_idx].key,"lon_dmn")){ rgr->lon_dmn_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_dmn_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"lon_nm")){ rgr->lon_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_nm_out")){ rgr->lon_nm_out=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_nm_out */ if(!strcmp(rgr_lst[rgr_var_idx].key,"lon_vrt_nm")){ rgr->lon_vrt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !lon_vrt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"plev_nm_in") || !strcmp(rgr_lst[rgr_var_idx].key,"plev_nm")){ rgr->plev_nm_in=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !plev_nm_in */ if(!strcmp(rgr_lst[rgr_var_idx].key,"ply_tri")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"csz")){ rgr->ply_tri_mth=nco_ply_tri_mth_csz; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"ctr") || !strcasecmp(rgr_lst[rgr_var_idx].val,"centroid") || !strcasecmp(rgr_lst[rgr_var_idx].val,"snl") || !strcasecmp(rgr_lst[rgr_var_idx].val,"mat")){ rgr->ply_tri_mth=nco_ply_tri_mth_ctr; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !ply_tri */ if(!strcmp(rgr_lst[rgr_var_idx].key,"sgs_frc_nm")){ rgr->sgs_frc_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !sgs_frc */ if(!strcmp(rgr_lst[rgr_var_idx].key,"sgs_msk_nm")){ rgr->sgs_msk_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !sgs_msk */ if(!strcmp(rgr_lst[rgr_var_idx].key,"sgs_nrm")){ rgr->sgs_nrm=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !sgs_nrm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"tst")){ rgr->tst=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !tst */ if(!strcmp(rgr_lst[rgr_var_idx].key,"msk_nm") || !strcmp(rgr_lst[rgr_var_idx].key,"mask_nm")){ rgr->msk_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); rgr->flg_msk_out=True; continue; } /* !msk_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"vrt_nm")){ rgr->vrt_nm=(char *)strdup(rgr_lst[rgr_var_idx].val); continue; } /* !vrt_nm */ if(!strcmp(rgr_lst[rgr_var_idx].key,"vrt_ntp") || !strcmp(rgr_lst[rgr_var_idx].key,"ntp_mth")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"lin") || !strcasecmp(rgr_lst[rgr_var_idx].val,"linear") || !strcasecmp(rgr_lst[rgr_var_idx].val,"lnr")){ rgr->ntp_mth=nco_ntp_lnr; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"log") || !strcasecmp(rgr_lst[rgr_var_idx].val,"logarithmic") || !strcasecmp(rgr_lst[rgr_var_idx].val,"lgr")){ rgr->ntp_mth=nco_ntp_log; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !ntp_mth */ if(!strcmp(rgr_lst[rgr_var_idx].key,"xtr_mth")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"nrs_ngh") || !strcasecmp(rgr_lst[rgr_var_idx].val,"ngh") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nearest_neighbor") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nn")){ rgr->xtr_mth=nco_xtr_fll_ngh; }else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"mss_val") || !strcasecmp(rgr_lst[rgr_var_idx].val,"msv") || !strcasecmp(rgr_lst[rgr_var_idx].val,"fll_val") || !strcasecmp(rgr_lst[rgr_var_idx].val,"missing_value")){ rgr->xtr_mth=nco_xtr_fll_msv; }else{ (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !xtr_mth */ if(!strcmp(rgr_lst[rgr_var_idx].key,"xtr_nsp") || !strcmp(rgr_lst[rgr_var_idx].key,"xtr_nbr_src_pnt") || !strcmp(rgr_lst[rgr_var_idx].key,"number_source_points") || !strcmp(rgr_lst[rgr_var_idx].key,"extrapolation_number_source_points")){ rgr->xtr_nsp=strtol(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtol",sng_cnv_rcd); continue; } /* !xtr_nsp */ if(!strcmp(rgr_lst[rgr_var_idx].key,"xtr_xpn") || !strcmp(rgr_lst[rgr_var_idx].key,"extrapolation_exponent") || !strcmp(rgr_lst[rgr_var_idx].key,"exponent_of_distance_in_extrapolation")){ rgr->xtr_xpn=strtod(rgr_lst[rgr_var_idx].val,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(rgr_lst[rgr_var_idx].val,"strtod",sng_cnv_rcd); continue; } /* !xtr_xpn */ if(!strcmp(rgr_lst[rgr_var_idx].key,"wgt_typ") || !strcmp(rgr_lst[rgr_var_idx].key,"weight_type")){ if(!strcasecmp(rgr_lst[rgr_var_idx].val,"con") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nco_con") || !strcasecmp(rgr_lst[rgr_var_idx].val,"conservative") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wgt_con")) rgr->wgt_typ=nco_wgt_con; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"idw") || !strcasecmp(rgr_lst[rgr_var_idx].val,"dwe") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nco_idw") || !strcasecmp(rgr_lst[rgr_var_idx].val,"distance_weighted") || !strcasecmp(rgr_lst[rgr_var_idx].val,"inverse_distance") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wgt_idw")) rgr->wgt_typ=nco_wgt_idw; else if(!strcasecmp(rgr_lst[rgr_var_idx].val,"bln") || !strcasecmp(rgr_lst[rgr_var_idx].val,"nco_bln") || !strcasecmp(rgr_lst[rgr_var_idx].val,"bilinear") || !strcasecmp(rgr_lst[rgr_var_idx].val,"wgt_bln")) rgr->wgt_typ=nco_wgt_bln; else { (void)fprintf(stderr,"%s: ERROR %s unable to parse \"%s\" option value \"%s\" (possible typo in value?), aborting...\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key,rgr_lst[rgr_var_idx].val); abort(); } /* !val */ continue; } /* !wgt_typ */ (void)fprintf(stderr,"%s: ERROR %s reports unrecognized key-value option to --rgr switch: %s\n",nco_prg_nm_get(),fnc_nm,rgr_lst[rgr_var_idx].key); nco_exit(EXIT_FAILURE); } /* !rgr_var_idx */ /* Eliminate sticky wickets: Give nfr precedence over grd */ if(rgr->flg_nfr && rgr->flg_grd) rgr->flg_grd=False; /* Revert to defaults for any names not specified on command-line */ if(!rgr->area_nm) rgr->area_nm=(char *)strdup("area"); /* [sng] Name of variable containing gridcell area */ if(!rgr->bnd_nm) rgr->bnd_nm=(char *)strdup("nvertices"); /* [sng] Name of dimension to employ for spatial bounds */ /* NB: CESM uses nbnd and ilev for temporal and vertical bounds, respectively (CESM outputs no horizontal spatial bounds). NCO defaults to nbnd for all bounds with two endpoints. */ if(!rgr->bnd_tm_nm) rgr->bnd_tm_nm=(char *)strdup("nbnd"); /* [sng] Name of dimension to employ for temporal bounds */ if(!rgr->col_nm_in) rgr->col_nm_in=(char *)strdup("ncol"); /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ if(!rgr->frc_nm) rgr->frc_nm=(char *)strdup("frac_b"); /* [sng] Name of variable containing gridcell fraction */ if(!rgr->ilev_nm_in) rgr->ilev_nm_in=(char *)strdup("ilev"); /* [sng] Name of input dimension to recognize as vertical dimension at layer interfaces */ if(!rgr->lat_bnd_nm) rgr->lat_bnd_nm=(char *)strdup("lat_bnds"); /* [sng] Name of rectangular boundary variable for latitude */ if(!rgr->lat_nm_in) rgr->lat_nm_in=(char *)strdup("lat"); /* [sng] Name of input dimension to recognize as latitude */ if(!rgr->lev_nm_in) rgr->lev_nm_in=(char *)strdup("lev"); /* [sng] Name of input dimension to recognize as vertical dimension at layer midpoints */ if(!rgr->lat_vrt_nm) rgr->lat_vrt_nm=(char *)strdup("lat_vertices"); /* [sng] Name of non-rectangular boundary variable for latitude */ if(!rgr->lat_wgt_nm) rgr->lat_wgt_nm=(char *)strdup("gw"); /* [sng] Name of variable containing latitude weights */ if(!rgr->lon_bnd_nm) rgr->lon_bnd_nm=(char *)strdup("lon_bnds"); /* [sng] Name of rectangular boundary variable for longitude */ if(!rgr->lon_nm_in) rgr->lon_nm_in=(char *)strdup("lon"); /* [sng] Name of dimension to recognize as longitude */ if(!rgr->lon_vrt_nm) rgr->lon_vrt_nm=(char *)strdup("lon_vertices"); /* [sng] Name of non-rectangular boundary variable for longitude */ if(!rgr->msk_nm) rgr->msk_nm=(char *)strdup("mask_b"); /* [sng] Name of variable containing destination mask */ if(!rgr->vrt_nm) rgr->vrt_nm=(char *)strdup("nv"); /* [sng] Name of dimension to employ for vertices */ if(!rgr->plev_nm_in) rgr->plev_nm_in=(char *)strdup("plev"); /* [sng] Name of variable to recognize as pure pressure coordinate */ /* Derived from defaults and command-line arguments */ // On second thought, do not strdup() these here. This way, NULL means user never specified lon/lat-out names // if(!rgr->col_nm_out) rgr->col_nm_out=(char *)strdup("ncol"); /* [sng] Name of dimension to output as horizontal spatial dimension on unstructured grid */ // if(!rgr->lat_nm_out) rgr->lat_nm_out=(char *)strdup("lat"); /* [sng] Name of dimension to output as latitude */ // if(!rgr->lon_nm_out) rgr->lon_nm_out=(char *)strdup("lon"); /* [sng] Name of dimension to output as longitude */ // if(!rgr->lat_nm_out) rgr->lat_nm_out=(char *)strdup(rgr_lat_nm_in); /* [sng] Name of output dimension for latitude */ // if(!rgr->lon_nm_out) rgr->lon_nm_out=(char *)strdup(rgr_lon_nm_in); /* [sng] Name of output dimension for longitude */ /* Free kvms */ if(rgr_lst) rgr_lst=nco_kvm_lst_free(rgr_lst,rgr_var_nbr); return rgr; } /* end nco_rgr_ini() */ int /* O [enm] Return code */ nco_ntp_vrt /* [fnc] Interpolate vertically */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Interpolate fields to new vertical grid specified in a vertical file */ const char fnc_nm[]="nco_ntp_vrt()"; /* [sng] Function name */ char *fl_tpl; /* [sng] Template file (vertical grid file) */ char *fl_pth_lcl=NULL; int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int in_id; /* I [id] Input netCDF file ID */ int tpl_id; /* [id] Input netCDF file ID (for vertical grid template) */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int dmn_idx; /* [idx] Dimension index */ int rec_idx; /* [idx] Record dimension index */ nco_bool FL_RTR_RMT_LCN; nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stderr,"%s: INFO %s obtaining vertical grid from %s\n",nco_prg_nm_get(),fnc_nm,rgr->fl_vrt); /* Duplicate (because nco_fl_mk_lcl() free()'s its fl_in) */ fl_tpl=(char *)strdup(rgr->fl_vrt); /* Make sure file is on local system and is readable or die trying */ fl_tpl=nco_fl_mk_lcl(fl_tpl,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_tpl,md_open,&bfr_sz_hnt,&tpl_id); /* Formula-terms for hybrid pressure vertical grid on unstructured CAM/EAM horizontal grid: prs_mdp[time,lev,col]=P0*hyam[lev] +PS[time,col]*hybm[lev] prs_ntf[time,lev,col]=P0*hyai[ilev]+PS[time,col]*hybi[ilev] */ /* Formula-terms for hybrid pressure vertical grid on ECMWF RLL horizontal grid: prs_mdp[time,lev,lat,lon]=hyam[lev] +exp(lnsp[time,lat,lon])*hybm[lev] prs_ntf[time,lev,lat,lon]=hyai[ilev]+exp(lnsp[time,lat,lon])*hybi[ilev] */ /* For simplicity and code re-use, all single-variable (not hybrid-variable) coordinate systems adopt "lev" semantics This includes pure pressure coordinates and eventually will include sigma, depth, and height coordinates Only hybrid coordinates will refer to the "ilev" levels and indices All single coordinate systems will refer to "lev" levels and indices */ int dpt_id; /* [id] Ocean depth ID */ int hyai_id=NC_MIN_INT; /* [id] Hybrid A coefficient at layer interfaces ID */ int hyam_id=NC_MIN_INT; /* [id] Hybrid A coefficient at layer midpoints ID */ int hybi_id=NC_MIN_INT; /* [id] Hybrid B coefficient at layer interfaces ID */ int hybm_id=NC_MIN_INT; /* [id] Hybrid B coefficient at layer midpoints ID */ int ilev_id=NC_MIN_INT; /* [id] Interface pressure ID */ int lev_id=NC_MIN_INT; /* [id] Midpoint pressure ID */ int p0_id=NC_MIN_INT; /* [id] Reference pressure ID */ int ps_id=NC_MIN_INT; /* [id] Surface pressure ID */ int plev_id; /* [id] Air pressure ID */ nco_bool flg_grd_hyb_cameam=False; /* [flg] Hybrid coordinate vertical grid uses CAM/EAM conventions */ nco_bool flg_grd_hyb_ecmwf=False; /* [flg] Hybrid coordinate vertical grid uses ECMWF conventions */ nco_bool flg_grd_in_dpt=False; /* [flg] Input depth coordinate vertical grid */ nco_bool flg_grd_in_hyb=False; /* [flg] Input hybrid coordinate vertical grid */ nco_bool flg_grd_in_prs=False; /* [flg] Input pressure coordinate vertical grid */ nco_bool flg_grd_out_dpt=False; /* [flg] Output depth coordinate vertical grid */ nco_bool flg_grd_out_hyb=False; /* [flg] Output hybrid coordinate vertical grid */ nco_bool flg_grd_out_prs=False; /* [flg] Output pressure coordinate vertical grid */ nco_bool flg_vrt_tm=False; /* [flg] Output depends on time-varying vertical grid */ nco_grd_vrt_typ_enm nco_vrt_grd_in=nco_vrt_grd_nil; /* [enm] Vertical grid type for input grid */ nco_grd_vrt_typ_enm nco_vrt_grd_out=nco_vrt_grd_nil; /* [enm] Vertical grid type for output grid */ nco_ntp_typ_enm ntp_mth=rgr->ntp_mth; /* [enm] Interpolation method */ nco_xtr_typ_enm xtr_mth=rgr->xtr_mth; /* [enm] Extrapolation method */ /* Determine output grid type */ if((rcd=nco_inq_varid_flg(tpl_id,"hyai",&hyai_id)) == NC_NOERR){ nco_vrt_grd_out=nco_vrt_grd_hyb; /* EAM */ flg_grd_out_hyb=True; }else if((rcd=nco_inq_varid_flg(tpl_id,"plev",&plev_id)) == NC_NOERR){ nco_vrt_grd_out=nco_vrt_grd_prs; /* NCEP */ flg_grd_out_prs=True; }else if((rcd=nco_inq_varid_flg(tpl_id,"depth",&dpt_id)) == NC_NOERR){ nco_vrt_grd_out=nco_vrt_grd_dpt; /* MPAS */ flg_grd_out_dpt=True; }else{ /* !hyai */ (void)fprintf(stdout,"%s: ERROR %s Unable to locate hybrid-sigma/pressure or pure-pressure vertical grid coordinate information in vertical grid file\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT ensure vertical grid coordinate file contains a valid vertical grid coordinate\n",nco_prg_nm_get()); return NCO_ERR; } /* !hyai */ if(flg_grd_out_hyb){ rcd=nco_inq_varid(tpl_id,"hyai",&hyai_id); rcd=nco_inq_varid(tpl_id,"hyam",&hyam_id); rcd=nco_inq_varid(tpl_id,"hybi",&hybi_id); rcd=nco_inq_varid(tpl_id,"hybm",&hybm_id); rcd=nco_inq_varid(tpl_id,"P0",&p0_id); rcd=nco_inq_varid_flg(tpl_id,"ilev",&ilev_id); rcd=nco_inq_varid_flg(tpl_id,"lev",&lev_id); rcd=nco_inq_varid_flg(tpl_id,"PS",&ps_id); } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ rcd=nco_inq_varid(tpl_id,"plev",&lev_id); } /* !flg_grd_out_prs */ if(flg_grd_out_dpt){ rcd=nco_inq_varid(tpl_id,"depth",&lev_id); } /* !flg_grd_out_dpt */ const int hyai_id_tpl=hyai_id; /* [id] Hybrid A coefficient at layer interfaces ID */ const int hyam_id_tpl=hyam_id; /* [id] Hybrid A coefficient at layer midpoints ID */ const int hybi_id_tpl=hybi_id; /* [id] Hybrid B coefficient at layer interfaces ID */ const int hybm_id_tpl=hybm_id; /* [id] Hybrid B coefficient at layer midpoints ID */ const int p0_id_tpl=p0_id; /* [id] Reference pressure ID */ const int ilev_id_tpl=ilev_id; /* [id] Interface pressure ID */ const int lev_id_tpl=lev_id; /* [id] Midpoint pressure ID */ const int ps_id_tpl=ps_id; /* [id] Surface pressure ID */ char *ilev_nm_in=NULL; /* [sng] Interface level name */ char *lev_nm_in; char *ilev_nm_out; char *lev_nm_out; char *plev_nm_in; /* [sng] Pure-pressure coordnate name */ char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ int *dmn_ids_in=NULL; /* [nbr] Input file dimension IDs */ int *dmn_ids_out=NULL; /* [nbr] Output file dimension IDs */ int *dmn_ids_rec=NULL; /* [id] Unlimited dimension IDs */ int dmn_nbr_ps; /* [nbr] Number of dimensions in PS variable */ int dmn_nbr_in; /* [nbr] Number of dimensions in input file */ int dmn_nbr_out; /* [nbr] Number of dimensions in output file */ int dmn_id_ilev_out=NC_MIN_INT; /* [id] Dimension ID for interface level in output file */ int dmn_id_lev_out=NC_MIN_INT; /* [id] Dimension ID for midpoint level in output file */ int dmn_id_ilev_in=NC_MIN_INT; /* [id] Dimension ID for interface level in file to be interpolated */ int dmn_id_lev_in=NC_MIN_INT; /* [id] Dimension ID for midpoint level in file to be interpolated */ int dmn_id_tm_in=NC_MIN_INT; /* [id] Dimension ID for time in file to be interpolated */ int dmn_nbr_rec; /* [nbr] Number of unlimited dimensions */ int dmn_idx_tm_in=NC_MIN_INT; /* [idx] Index of record coordinate in input hybrid coordinate PS field */ long *dmn_cnt_in=NULL; long *dmn_cnt_out=NULL; long *dmn_srt=NULL; long ilev_nbr_in; long lev_nbr_in; long ilev_nbr_out; long lev_nbr_out; long tm_idx=0L; /* [idx] Current timestep */ long tm_nbr=1L; /* [idx] Number of timesteps in vertical grid */ long tm_nbr_in=1L; /* [nbr] Number of timesteps in input vertical grid definition */ long tm_nbr_out=1L; /* [nbr] Number of timesetps in output vertical grid definition */ size_t grd_idx; /* [idx] Gridcell index */ size_t grd_sz_in=1L; /* [nbr] Number of elements in single layer of input grid */ size_t grd_sz_out=1L; /* [nbr] Number of elements in single layer of output grid */ size_t idx_fst; /* [idx] Index-offset to current surface pressure timeslice */ if(flg_grd_out_hyb){ /* Interrogate hyai/hyam to obtain ilev/lev dimensions */ rcd=nco_inq_vardimid(tpl_id,hyai_id,&dmn_id_ilev_out); rcd=nco_inq_vardimid(tpl_id,hyam_id,&dmn_id_lev_out); rcd=nco_inq_dimlen(tpl_id,dmn_id_ilev_out,&ilev_nbr_out); rcd=nco_inq_dimlen(tpl_id,dmn_id_lev_out,&lev_nbr_out); rcd=nco_inq_dimname(tpl_id,dmn_id_ilev_out,dmn_nm); ilev_nm_out=strdup(dmn_nm); rcd=nco_inq_dimname(tpl_id,dmn_id_lev_out,dmn_nm); lev_nm_out=strdup(dmn_nm); /* Interrogate PS, if any, for horizontal dimensions */ if(ps_id_tpl != NC_MIN_INT){ rcd=nco_inq_varndims(tpl_id,ps_id,&dmn_nbr_ps); dmn_nbr_out=dmn_nbr_ps; dmn_ids_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_cnt_out=(long *)nco_malloc((dmn_nbr_out+1)*sizeof(long)); dmn_srt=(long *)nco_malloc((dmn_nbr_out+1)*sizeof(long)); rcd=nco_inq_vardimid(tpl_id,ps_id,dmn_ids_out); rcd=nco_inq_unlimdims(tpl_id,&dmn_nbr_rec,(int *)NULL); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd=nco_inq_unlimdims(tpl_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ rcd=nco_inq_dimlen(tpl_id,dmn_ids_out[dmn_idx],dmn_cnt_out+dmn_idx); /* 20190330: Allow possibility that PS has time dimension > 1 We want horizontal not temporal dimensions to contribute to grd_sz Temporal dimension is usually unlimited Only multiply grd_sz by fixed (non-unlimited) dimension sizes Corner-case exception when PS spatial dimension on unstructured grid is unlimited */ for(rec_idx=0;rec_idx<dmn_nbr_rec;rec_idx++) if(dmn_ids_out[dmn_idx] == dmn_ids_rec[rec_idx]) break; if(rec_idx == dmn_nbr_rec || dmn_nbr_out == 1) grd_sz_out*=dmn_cnt_out[dmn_idx]; if(rec_idx != dmn_nbr_rec && dmn_nbr_out > 1 && dmn_cnt_out[dmn_idx] > 1L){ tm_nbr_out=dmn_cnt_out[dmn_idx]; if(tm_nbr_out > 1L) flg_vrt_tm=True; } /* tm_nbr_out > 1 */ dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); } /* !ps_id_tpl */ } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ /* Interrogate plev to obtain plev dimensions */ rcd=nco_inq_vardimid(tpl_id,lev_id,&dmn_id_lev_out); rcd=nco_inq_dimlen(tpl_id,dmn_id_lev_out,&lev_nbr_out); rcd=nco_inq_dimname(tpl_id,dmn_id_lev_out,dmn_nm); ilev_nbr_out=lev_nbr_out; } /* !flg_grd_out_prs */ double *hyai_out=NULL; /* [frc] Hybrid A coefficient at layer interfaces on output grid */ double *hyam_out=NULL; /* [frc] Hybrid A coefficient at layer midpoints on output grid */ double *hybi_out=NULL; /* [frc] Hybrid B coefficient at layer interfaces on output grid */ double *hybm_out=NULL; /* [frc] Hybrid B coefficient at layer midpoints on output grid */ double *ilev_out=NULL; /* [hPa] Interface pressure on output grid */ double *lev_out=NULL; /* [hPa] Midpoint pressure on output grid */ double *ps_out=NULL; /* [Pa] Surface pressure on output grid */ double *prs_mdp_out=NULL; /* [Pa] Midpoint pressure on output grid */ double *prs_ntf_out=NULL; /* [Pa] Interface pressure on output grid */ double p0_out; /* [Pa] Reference pressure on output grid */ long ilev_idx; /* [idx] Interface level index */ long lev_idx; /* [idx] Level index */ const nc_type crd_typ_out=NC_DOUBLE; nc_type var_typ_rgr; /* [enm] Variable type used during regridding */ var_typ_rgr=NC_DOUBLE; /* NB: Perform interpolation in double precision */ if(flg_grd_out_hyb){ hyai_out=(double *)nco_malloc(ilev_nbr_out*nco_typ_lng(var_typ_rgr)); hyam_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); hybi_out=(double *)nco_malloc(ilev_nbr_out*nco_typ_lng(var_typ_rgr)); hybm_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); ilev_out=(double *)nco_malloc(ilev_nbr_out*nco_typ_lng(var_typ_rgr)); lev_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(tpl_id,hyai_id,hyai_out,crd_typ_out); rcd=nco_get_var(tpl_id,hyam_id,hyam_out,crd_typ_out); rcd=nco_get_var(tpl_id,hybi_id,hybi_out,crd_typ_out); rcd=nco_get_var(tpl_id,hybm_id,hybm_out,crd_typ_out); rcd=nco_get_var(tpl_id,p0_id,&p0_out,crd_typ_out); if(ilev_id_tpl != NC_MIN_INT){ rcd=nco_get_var(tpl_id,ilev_id,ilev_out,crd_typ_out); }else{ /* p0 is in Pa but ilev traditionally given in hPa */ for(ilev_idx=0;ilev_idx<ilev_nbr_out;ilev_idx++) ilev_out[ilev_idx]=p0_out*(hyai_out[ilev_idx]+hybi_out[ilev_idx])/100.0; } /* !ilev_id_tpl */ if(lev_id_tpl != NC_MIN_INT){ rcd=nco_get_var(tpl_id,lev_id,lev_out,crd_typ_out); }else{ /* p0 is in Pa but lev traditionally given in hPa */ for(lev_idx=0;lev_idx<lev_nbr_out;lev_idx++) lev_out[lev_idx]=p0_out*(hyam_out[lev_idx]+hybm_out[lev_idx])/100.0; } /* !ilev_id_tpl */ } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ lev_out=(double *)nco_malloc(lev_nbr_out*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(tpl_id,lev_id,lev_out,crd_typ_out); } /* !flg_grd_out_prs */ /* For vertical interpolation (unlike horizontal regridding), the destination grid is known a priori Straightforward copy all variables and attributes that define grid from fl_tpl to output would work in theory, but would not allow dynamic identification and relabeling of names */ /* if(flg_grd_out_hyb){ const int vrt_grd_lst_nbr=8; const char *vrt_grd_lst[]={"/hyai","/hyam","/hybi","/hybm","/ilev","/lev","/P0","/PS"}; } if(flg_grd_out_prs){ const int vrt_grd_lst_nbr=1; const char *vrt_grd_lst[]={"/plev"}; } */ /* Above this line, fl_tpl and tpl_id refer to vertical coordinate file (i.e., template file) Below this line, fl_in and in_id refer to input file to be vertically regridded Do not close template file until all grid variables have been copied For maximum efficiency, do this after defining all interpolated variables in output That way no file needs to exit define mode or enter data mode more than once However this requires keeping template file, input data file, and output file simulataneously open */ in_id=rgr->in_id; out_id=rgr->out_id; /* Determine input grid type */ if(rgr->plev_nm_in) plev_nm_in=rgr->plev_nm_in; if((rcd=nco_inq_varid_flg(in_id,"hyai",&hyai_id)) == NC_NOERR){ nco_vrt_grd_in=nco_vrt_grd_hyb; /* EAM */ flg_grd_in_hyb=True; }else if((rcd=nco_inq_varid_flg(in_id,plev_nm_in,&plev_id)) == NC_NOERR){ nco_vrt_grd_in=nco_vrt_grd_prs; /* NCEP */ flg_grd_in_prs=True; }else if((rcd=nco_inq_varid_flg(in_id,"depth",&dpt_id)) == NC_NOERR){ nco_vrt_grd_in=nco_vrt_grd_dpt; /* NCEP */ flg_grd_in_dpt=True; }else{ /* !hyai */ (void)fprintf(stdout,"%s: ERROR %s Unable to locate hybrid-sigma/pressure or pure-pressure vertical grid coordinate information in input file\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT only invoke vertical interpolation on files that contain variables with vertical dimensions, and with known vertical coordinate variable names. These default to \"hyai\" for hybrid, \"plev\" for pressure, \"depth\" for depth. See http://nco.sf.net/nco.html#lev_nm for options to change these names at run-time, e.g., \"--rgr plev_nm=vrt_nm\"\n",nco_prg_nm_get()); return NCO_ERR; } /* !hyai */ /* Sanity checks: One type of input and one type of output grid detected */ assert(!(flg_grd_in_hyb && flg_grd_in_prs)); assert(!(flg_grd_in_hyb && flg_grd_in_dpt)); assert(!(flg_grd_in_prs && flg_grd_in_dpt)); assert(flg_grd_in_hyb || flg_grd_in_prs || flg_grd_in_dpt); assert(!(flg_grd_out_hyb && flg_grd_out_prs)); assert(!(flg_grd_out_hyb && flg_grd_out_dpt)); assert(!(flg_grd_out_prs && flg_grd_out_dpt)); assert(flg_grd_out_hyb || flg_grd_out_prs || flg_grd_out_dpt); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: DEBUG Input grid flags : flg_grd_in_hyb = %d, flg_grd_in_prs = %d, flg_grd_in_dpt = %d\n",nco_prg_nm_get(),flg_grd_in_hyb,flg_grd_in_prs,flg_grd_in_dpt); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: DEBUG Output grid flags: flg_grd_out_hyb = %d, flg_grd_out_prs = %d, flg_grd_out_dpt = %d\n",nco_prg_nm_get(),flg_grd_out_hyb,flg_grd_out_prs,flg_grd_out_dpt); /* 20191219: This block is not used, deprecate it? Or use once new coordinates like altitude, depth supported? */ nco_vrt_ntp_typ_enm nco_vrt_ntp_typ=nco_ntp_nil; /* Vertical interpolation type */ if(nco_vrt_grd_in == nco_vrt_grd_hyb && nco_vrt_grd_out == nco_vrt_grd_hyb) nco_vrt_ntp_typ=nco_ntp_hyb_to_hyb; if(nco_vrt_grd_in == nco_vrt_grd_hyb && nco_vrt_grd_out == nco_vrt_grd_prs) nco_vrt_ntp_typ=nco_ntp_hyb_to_prs; if(nco_vrt_grd_in == nco_vrt_grd_prs && nco_vrt_grd_out == nco_vrt_grd_hyb) nco_vrt_ntp_typ=nco_ntp_prs_to_hyb; if(nco_vrt_grd_in == nco_vrt_grd_prs && nco_vrt_grd_out == nco_vrt_grd_prs) nco_vrt_ntp_typ=nco_ntp_prs_to_prs; assert(nco_vrt_ntp_typ != nco_ntp_nil); /* Variables on input grid, i.e., on grid in data file to be interpolated */ if(flg_grd_in_hyb){ rcd=nco_inq_varid(in_id,"hyai",&hyai_id); rcd=nco_inq_varid(in_id,"hyam",&hyam_id); rcd=nco_inq_varid(in_id,"hybi",&hybi_id); rcd=nco_inq_varid(in_id,"hybm",&hybm_id); /* 20190602: ECMWF hybrid vertical grid parameters and dimensions differ from CAM/EAM: ECMWF defines vertical dimensions "nhym" and "nhyi" specifically for hy[ab][im] and uses "lev" and "lev_2" for all other variables, whereas CAM/EAM uses same dimensions "lev" and "ilev" for all vertical variables including hybrid coefficients ECMWF provides "hya?" as a constant in Pa and "hyb?" as a dimensionless coefficient of PS, whereas CAM/EAM provides "hya?" and "hyb?" both as dimensionless coefficients of P0 and PS ECMWF provides "lev" and "lev_2" with midpoint and surface pressure indices (not values), respectively, whereas CAM/EAM provides "lev" and "ilev" coordinate values in hPa ECMWF provides dimensionless "lnsp" for log(surface pressure) whereas CAM/EAM provides "PS" for surface pressure in Pa ECMWF "lnsp" has degenerate level dimension "lev_2" whereas CAM/EAM "PS" has no "ilev" dimension ECMWF uses hya? instead of reference pressure whereas CAM/EAM provides "P0" in hPa */ if((rcd=nco_inq_varid_flg(in_id,"lnsp",&ps_id)) == NC_NOERR) flg_grd_hyb_ecmwf=True; else if((rcd=nco_inq_varid_flg(in_id,"PS",&ps_id)) == NC_NOERR) flg_grd_hyb_cameam=True; else{ (void)fprintf(stderr,"%s: ERROR %s Unable to find surface pressure variable required for hybrid grid in input file\n",nco_prg_nm_get(),fnc_nm); abort(); } /* !rcd */ if(flg_grd_hyb_cameam){ rcd=nco_inq_varid(in_id,"P0",&p0_id); ilev_id=NC_MIN_INT; lev_id=NC_MIN_INT; if(ilev_id_tpl == NC_MIN_INT) rcd=nco_inq_varid_flg(in_id,"ilev",&ilev_id); if(lev_id_tpl == NC_MIN_INT) rcd=nco_inq_varid_flg(in_id,"lev",&lev_id); } /* !flg_grd_hyb_cameam */ /* 20190603: We require ECMWF IFS input to have a "lev" coordinate so we can use "lev" dimension not "nhyb" */ if(flg_grd_hyb_ecmwf) rcd=nco_inq_varid(in_id,"lev",&lev_id); } /* !flg_grd_in_hyb */ if(flg_grd_in_prs){ rcd=nco_inq_varid(in_id,plev_nm_in,&lev_id); if((rcd=nco_inq_varid_flg(in_id,"PS",&ps_id)) == NC_NOERR){ /* Output file creation procedure discriminates between input surface pressure dimensioned as CAM/EAM vs. ECMWF */ flg_grd_hyb_cameam=True; if(flg_grd_out_hyb && (ps_id_tpl == NC_MIN_INT)) (void)fprintf(stderr,"%s: INFO %s detects variable PS (canonical name for spatially varying surface pressure field in hybrid grids) in pure-pressure input data file. PS will be copied directly from pure-pressure grid input dataset to, and used to construct the pressures of, the output hybrid-coordinate data file.\n",nco_prg_nm_get(),fnc_nm); if(flg_grd_out_hyb && (ps_id_tpl != NC_MIN_INT)) (void)fprintf(stderr,"%s: INFO %s detects variable PS (canonical name for spatially varying surface pressure field in hybrid grids) in both vertical-grid file and pure-pressure input data file. The vertical grid-file takes precedence. PS will be copied directly from vertical-grid file to, and used to construct the pressures of, the output hybrid-coordinate data file. PS in input pure-pressure file will be ignored.\n",nco_prg_nm_get(),fnc_nm); }else{ if(flg_grd_out_hyb && (ps_id_tpl == NC_MIN_INT)){ (void)fprintf(stderr,"%s: ERROR %s does not find variable PS (canonical name for spatially varying surface pressure field in hybrid grids) in pure-pressure input data file or in vertical grid-file for hybrid-pressure output. PS must be present in at least one of these files in order to construct the output hybrid-coordinate pressures.\nHINT: Append a valid PS to the inpud data file or vertical grid-file.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !ps_id_tpl */ } /* !ps_id */ } /* !flg_grd_in_prs */ if(flg_grd_in_dpt){ rcd=nco_inq_varid(in_id,"depth",&lev_id); } /* !flg_grd_in_dpt */ const int ilev_id_in=ilev_id; /* [id] Interface pressure ID */ const int lev_id_in=lev_id; /* [id] Midpoint pressure ID */ const int ps_id_in=ps_id; /* [id] Surface pressure ID */ /* Identify all record-dimensions in input file */ rcd=nco_inq_unlimdims(in_id,&dmn_nbr_rec,(int *)NULL); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ if(flg_grd_in_hyb){ /* Get hybrid vertical information first */ rcd=nco_inq_varndims(in_id,ps_id,&dmn_nbr_in); rcd=nco_inq_vardimid(in_id,hyai_id,&dmn_id_ilev_in); if(flg_grd_hyb_cameam) rcd=nco_inq_vardimid(in_id,hyam_id,&dmn_id_lev_in); if(flg_grd_hyb_ecmwf) rcd=nco_inq_vardimid(in_id,lev_id,&dmn_id_lev_in); rcd=nco_inq_dimlen(in_id,dmn_id_ilev_in,&ilev_nbr_in); rcd=nco_inq_dimlen(in_id,dmn_id_lev_in,&lev_nbr_in); rcd=nco_inq_dimname(in_id,dmn_id_ilev_in,dmn_nm); ilev_nm_in=strdup(dmn_nm); rcd=nco_inq_dimname(in_id,dmn_id_lev_in,dmn_nm); lev_nm_in=strdup(dmn_nm); } /* !flg_grd_in_hyb */ if(flg_grd_in_prs){ /* Interrogate plev to obtain plev dimensions */ rcd=nco_inq_vardimid(in_id,lev_id,&dmn_id_lev_in); rcd=nco_inq_dimlen(in_id,dmn_id_lev_in,&lev_nbr_in); rcd=nco_inq_dimname(in_id,dmn_id_lev_in,dmn_nm); lev_nm_in=strdup(dmn_nm); /* Define horizontal grid if no PS is provided (i.e., pure-pressure to pure-pressure interpolation) */ if(!flg_grd_out_hyb){ /* Problem: What is horizontal grid size of pressure grid file? Algorithm: Examine first multi-dimensional variable that includes plev dimension Assume horizontal dimensions vary more rapidly than (i.e., follow) plev Compute horizontal grid size accordingly Set output horizontal size to input horizontal size */ int var_nbr; /* [nbr] Number of variables in file */ int var_idx; /* [idx] Index over variables in file */ rcd=nco_inq(in_id,&dmn_nbr_in,&var_nbr,(int *)NULL,(int *)NULL); dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_cnt_in=(long *)nco_malloc(dmn_nbr_in*sizeof(long)); for(var_idx=0;var_idx<var_nbr;var_idx++){ rcd=nco_inq_varndims(in_id,var_idx,&dmn_nbr_in); rcd=nco_inq_vardimid(in_id,var_idx,dmn_ids_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++) if(dmn_ids_in[dmn_idx] == dmn_id_lev_in) break; /* Does current variable have lev dimension? */ if(dmn_idx < dmn_nbr_in){ /* Yes. Do any dimensions vary more rapidly than lev? */ if(dmn_idx < dmn_nbr_in-1){ /* Yes. Assume remaining dimension are horizontal spatial dimensions */ char var_nm[NC_MAX_NAME+1L]; (void)nc_inq_varname(in_id,var_idx,var_nm); for(int dmn_idx_hrz=dmn_idx+1;dmn_idx_hrz<dmn_nbr_in;dmn_idx_hrz++){ rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx_hrz],dmn_cnt_in+dmn_idx_hrz); grd_sz_in*=dmn_cnt_in[dmn_idx_hrz]; } /* !dmn_idx_hrz */ break; } /* !dmn_idx */ } /* !dmn_idx */ } /* !var_idx */ assert(var_idx != var_nbr); grd_sz_out=grd_sz_in; } /* !flg_grd_out_hyb */ } /* !flg_grd_in_prs */ double *hyai_in=NULL; /* [frc] Hybrid A coefficient at layer interfaces on input grid */ double *hyam_in=NULL; /* [frc] Hybrid A coefficient at layer midpoints on input grid */ double *hybi_in=NULL; /* [frc] Hybrid B coefficient at layer interfaces on input grid */ double *hybm_in=NULL; /* [frc] Hybrid B coefficient at layer midpoints on input grid */ double *lev_in=NULL; /* [Pa] Air pressure on input grid */ double *prs_mdp_in=NULL; /* [Pa] Midpoint pressure on input grid */ double *prs_ntf_in=NULL; /* [Pa] Interface pressure on input grid */ double *ps_in=NULL; /* [Pa] Surface pressure on input grid */ double p0_in; /* [Pa] Reference pressure on input grid */ if(flg_grd_in_hyb){ hyai_in=(double *)nco_malloc(ilev_nbr_in*nco_typ_lng(var_typ_rgr)); hyam_in=(double *)nco_malloc(lev_nbr_in*nco_typ_lng(var_typ_rgr)); hybi_in=(double *)nco_malloc(ilev_nbr_in*nco_typ_lng(var_typ_rgr)); hybm_in=(double *)nco_malloc(lev_nbr_in*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(in_id,hyai_id,hyai_in,crd_typ_out); rcd=nco_get_var(in_id,hyam_id,hyam_in,crd_typ_out); rcd=nco_get_var(in_id,hybi_id,hybi_in,crd_typ_out); rcd=nco_get_var(in_id,hybm_id,hybm_in,crd_typ_out); if(flg_grd_hyb_cameam) rcd=nco_get_var(in_id,p0_id,&p0_in,crd_typ_out); /* ECMWF distributes IFS forecasts with lnsp = log(surface pressure) */ if(flg_grd_hyb_ecmwf){ /* Decompose ECMWF hya? convention into CAM/EAM-like product of P0 and hya? */ p0_in=100000.0; for(size_t idx=0;idx<lev_nbr_in;idx++){ hyai_in[idx]/=p0_in; hyam_in[idx]/=p0_in; } /* !idx */ } /* flg_grd_hyb_ecmwf */ } /* !flg_grd_in_hyb */ if(flg_grd_in_prs){ lev_in=(double *)nco_malloc(lev_nbr_in*nco_typ_lng(var_typ_rgr)); rcd=nco_get_var(in_id,lev_id,lev_in,crd_typ_out); } /* !flg_grd_in_prs */ /* Always obtain surface pressure if input or output grid is hybrid */ if(flg_grd_in_hyb || flg_grd_out_hyb){ /* Copy horizontal grid information from input file LHS variables were set above if PS is in template file */ if(ps_id_tpl == NC_MIN_INT){ /* NB: dmn_nbr_in/out in this block refer only to horizontal dimensions necessary to define PS */ rcd=nco_inq_varndims(in_id,ps_id,&dmn_nbr_in); /* This is harmlessly repeated for hybrid input files */ dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_cnt_in=(long *)nco_malloc((dmn_nbr_in+1)*sizeof(long)); if(!dmn_srt) dmn_srt=(long *)nco_malloc((dmn_nbr_in+1)*sizeof(long)); /* NB: Only allocate dmn_srt once */ rcd=nco_inq_vardimid(in_id,ps_id,dmn_ids_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_in+dmn_idx); /* 20190330: Allow possibility that PS has time dimension > 1 We want horizontal not temporal dimensions to contribute to grd_sz Temporal dimension is usually unlimited Only multiply grd_sz by fixed (non-unlimited) dimension sizes Corner-case exception when PS spatial dimension on unstructured grid is unlimited */ for(rec_idx=0;rec_idx<dmn_nbr_rec;rec_idx++) if(dmn_ids_in[dmn_idx] == dmn_ids_rec[rec_idx]) break; if(rec_idx == dmn_nbr_rec || dmn_nbr_in == 1) grd_sz_in*=dmn_cnt_in[dmn_idx]; if(rec_idx != dmn_nbr_rec && dmn_nbr_in > 1 && dmn_cnt_in[dmn_idx] > 1L){ dmn_id_tm_in=dmn_ids_in[dmn_idx]; dmn_idx_tm_in=dmn_idx; tm_nbr_in=dmn_cnt_in[dmn_idx_tm_in]; if(tm_nbr_in > 1L) flg_vrt_tm=True; } /* tm_nbr_in > 1 */ dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ /* Given all input PS information, define output PS information */ dmn_nbr_ps=dmn_nbr_out=dmn_nbr_in; dmn_ids_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_cnt_out=(long *)nco_malloc((dmn_nbr_out+1)*sizeof(long)); /* fxm: next line works for hyb_in and is buggy for prs_in */ memcpy(dmn_ids_out,dmn_ids_in,dmn_nbr_in*sizeof(int)); memcpy(dmn_cnt_out,dmn_cnt_in,dmn_nbr_in*sizeof(long)); grd_sz_out=grd_sz_in; tm_nbr_out=tm_nbr_in; }else{ /* !ps_id_tpl */ /* 20200825: We have already defined grd_sz_out if PS is in template file We have already defined grd_sz_in and grd_sz_out := grd_sz_in when PS not in template file We have already defined grd_sz_in if input file is pure-pressure However, we have not yet defined grd_sz_in if input file is hybrid Expectation is that grd_sz_in (from input file) = grd_sz_out (from template file) An independent check on this would examine dimension sizes in input file Such a check would immediately flag horizontal mismatches between vertical file and input file The check could not rely on PS being present in input file The check could/should examine the first horizontal variable in input file This would require a lot of code, so we just assume it is true */ grd_sz_in=grd_sz_out; } /* !ps_id_tpl */ /* Timestep sequencing NB: tm_nbr_??? variables count timesteps in vertical grid definitions These are not necessarily the same as the number of timesteps in either file Time-invariant hybrid or pure-pressure coordinates are valid vertical grids for timeseries Usually hybrid grids have as many timesteps in the grids as in the timeseries Usually pressure grids are time-invariant (as of 20190511 time-varying pure pressure grids are still not supported) This implementation interpolates timeseries to/from time-invariant vertical grids in one OpenMP call! */ if(tm_nbr_in > 1L || tm_nbr_out > 1L){ if(tm_nbr_in > tm_nbr_out) assert((float)tm_nbr_in/(float)tm_nbr_out == tm_nbr_in/tm_nbr_out); else assert((float)tm_nbr_out/(float)tm_nbr_in == tm_nbr_out/tm_nbr_in); } /* !tm_nbr_in */ tm_nbr=tm_nbr_in > tm_nbr_out ? tm_nbr_in : tm_nbr_out; /* Sanity checks */ if(grd_sz_in != grd_sz_out || tm_nbr_in != tm_nbr_out) (void)fprintf(stdout,"%s: ERROR %s reports that temporal or horizontal spatial dimensions differ: grd_sz_in = %ld != %ld = grd_sz_out, and/or tm_nbr_in = %ld != %ld = tm_nbr_out\n",nco_prg_nm_get(),fnc_nm,grd_sz_in,grd_sz_out,tm_nbr_in,tm_nbr_out); assert(grd_sz_in == grd_sz_out); assert(tm_nbr_in == tm_nbr_out); ps_in=(double *)nco_malloc_dbg(tm_nbr_in*grd_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() ps_in value buffer"); /* Surface pressure comes from either hybrid vertical grid-files, hybrid data files, or pressure data files that provide surface pressure */ if(flg_grd_in_hyb || (flg_grd_in_prs && ps_id_tpl == NC_MIN_INT)) rcd=nco_get_var(in_id,ps_id,ps_in,crd_typ_out); /* ECMWF distributes IFS forecasts with lnsp = log(surface pressure) */ if(flg_grd_hyb_ecmwf){ /* Convert ECMWF-provided log(surface_pressure) to surface_pressure */ const size_t ps_sz_in=tm_nbr_in*grd_sz_in; /* [nbr] Number of elements in ps_in */ for(size_t idx=0;idx<ps_sz_in;idx++) ps_in[idx]=exp(ps_in[idx]); } /* flg_grd_hyb_ecmwf */ /* Finally have enough information to allocate output pressure grid */ ps_out=(double *)nco_malloc_dbg(tm_nbr_out*grd_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() ps_out value buffer"); /* Get PS from output horizontal grid, if available, otherwise copy from input horizontal grid */ if(ps_id_tpl != NC_MIN_INT){ rcd=nco_get_var(tpl_id,ps_id_tpl,ps_out,crd_typ_out); /* NB: Here we read from tpl_id one last time */ }else{ memcpy(ps_out,ps_in,tm_nbr_in*grd_sz_in*nco_typ_lng(var_typ_rgr)); } /* !ps_id_tpl */ } /* ! */ /* Compare input and output surface pressure fields to determine whether subterranean extrapolation required */ nco_bool flg_add_msv_att; /* [flg] Extrapolation requires _FillValue */ flg_add_msv_att=False; /* Extrapolation type xtr_fll_msv may cause need to create _FillValue attributes */ if(xtr_mth == nco_xtr_fll_msv){ const size_t ps_sz=tm_nbr*grd_sz_in; // [nbr] Size of surface-pressure field double *prs_max_in=NULL; /* [Pa] Maximum midpoint pressure on input grid */ double *prs_max_out=NULL; /* [Pa] Maximum midpoint pressure on output grid */ double *prs_min_in=NULL; /* [Pa] Minimum midpoint pressure on input grid */ double *prs_min_out=NULL; /* [Pa] Minimum midpoint pressure on output grid */ long idx_lev_max; // [idx] Index of midpoint level with greatest pressure long idx_lev_min; // [idx] Index of midpoint level with lowest pressure size_t idx; // [idx] Counting index prs_max_in=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_max_in value buffer"); prs_max_out=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_max_out value buffer"); prs_min_in=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_min_in value buffer"); prs_min_out=(double *)nco_malloc_dbg(ps_sz*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_min_out value buffer"); if(flg_grd_in_hyb){ // fxm: assumes hybrid grid has least/greatest pressure at top/bottom level idx_lev_max=lev_nbr_in-1; idx_lev_min=0L; for(tm_idx=0;tm_idx<tm_nbr;tm_idx++){ idx_fst=tm_idx*grd_sz_in; for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++){ prs_max_in[grd_idx+idx_fst]=p0_in*hyam_in[idx_lev_max]+ps_in[idx_fst+grd_idx]*hybm_in[idx_lev_max]; prs_min_in[grd_idx+idx_fst]=p0_in*hyam_in[idx_lev_min]+ps_in[idx_fst+grd_idx]*hybm_in[idx_lev_min]; } /* !grd_idx */ } /* !tm_idx */ } /* !flg_grd_in_hyb */ if(flg_grd_out_hyb){ // fxm: assumes hybrid grid has least/greatest pressure at top/bottom level idx_lev_max=lev_nbr_out-1; idx_lev_min=0L; for(tm_idx=0;tm_idx<tm_nbr;tm_idx++){ idx_fst=tm_idx*grd_sz_out; for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++){ prs_max_out[grd_idx+idx_fst]=p0_out*hyam_out[idx_lev_max]+ps_out[idx_fst+grd_idx]*hybm_out[idx_lev_max]; prs_min_out[grd_idx+idx_fst]=p0_out*hyam_out[idx_lev_min]+ps_out[idx_fst+grd_idx]*hybm_out[idx_lev_min]; } /* !grd_idx */ } /* !tm_idx */ } /* !flg_grd_out_hyb */ if(flg_grd_in_prs){ double lev_in_max; double lev_in_min; if(lev_in[0] < lev_in[1]) lev_in_max=lev_in[lev_nbr_in-1]; else lev_in_max=lev_in[0]; if(lev_in[0] < lev_in[1]) lev_in_min=lev_in[0]; else lev_in_max=lev_in[lev_nbr_in-1]; for(size_t idx_in=0;idx_in<ps_sz;idx_in++) prs_max_in[idx_in]=lev_in_max; for(size_t idx_in=0;idx_in<ps_sz;idx_in++) prs_min_in[idx_in]=lev_in_min; } /* !flg_grd_in_prs */ if(flg_grd_out_prs){ double lev_out_max; double lev_out_min; if(lev_out[0] < lev_out[1]) lev_out_max=lev_out[lev_nbr_out-1]; else lev_out_max=lev_out[0]; if(lev_out[0] < lev_out[1]) lev_out_min=lev_out[0]; else lev_out_min=lev_out[lev_nbr_out-1]; for(size_t idx_out=0;idx_out<ps_sz;idx_out++) prs_max_out[idx_out]=lev_out_max; for(size_t idx_out=0;idx_out<ps_sz;idx_out++) prs_min_out[idx_out]=lev_out_min; } /* !flg_grd_out_prs */ for(idx=0;idx<ps_sz;idx++) if(prs_max_out[idx] > prs_max_in[idx]) break; if(idx < ps_sz) flg_add_msv_att=True; for(idx=0;idx<ps_sz;idx++) if(prs_min_out[idx] < prs_min_in[idx]) break; if(idx < ps_sz) flg_add_msv_att=True; if(flg_add_msv_att && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports at least one point in at least one output level requires extrapolation (not interpolation). Will ensure that all interpolated fields have _FillValue attribute.\n",nco_prg_nm_get(),fnc_nm); if(prs_max_in) prs_max_in=(double *)nco_free(prs_max_in); if(prs_max_out) prs_max_out=(double *)nco_free(prs_max_out); if(prs_min_in) prs_min_in=(double *)nco_free(prs_min_in); if(prs_min_out) prs_min_out=(double *)nco_free(prs_min_out); } /* !xtr_mth */ /* Lay-out regridded file */ //(void)fprintf(stdout,"%s: DEBUG quark1 dmn_nbr_out = %d, dmn_nbr_ps = %d\n",nco_prg_nm_get(),dmn_nbr_out,dmn_nbr_ps); /* Use explicitly specified output names, if any, otherwise use template names (either explicitly specified or discovered by fuzzing) */ if(rgr->lev_nm_out) lev_nm_out=rgr->lev_nm_out; if(rgr->ilev_nm_out){ if(flg_grd_out_hyb) ilev_nm_out=rgr->ilev_nm_out; if(flg_grd_out_prs) lev_nm_out=rgr->ilev_nm_out; } /* !ilev_nm_out */ if(flg_grd_out_prs){ /* Unless user explicitly specifies output name, use same name as input */ if(!rgr->lev_nm_out) lev_nm_out=(char *)strdup(plev_nm_in); /* Hybrid-sigma/pressure interface variables, if any, must also be output to pure-pressure files on lev grid */ ilev_nm_out=(char *)strdup(lev_nm_out); } /* !flg_grd_out_prs */ /* Define new vertical dimensions before all else */ if(flg_grd_out_hyb){ rcd=nco_def_dim(out_id,ilev_nm_out,ilev_nbr_out,&dmn_id_ilev_out); rcd=nco_def_dim(out_id,lev_nm_out,lev_nbr_out,&dmn_id_lev_out); /* Horizontal dimensions necessary to define PS variable */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ if(ps_id_tpl != NC_MIN_INT){ rcd=nco_inq_dimname(tpl_id,dmn_ids_out[dmn_idx],dmn_nm); }else{ rcd=nco_inq_dimname(in_id,dmn_ids_in[dmn_idx],dmn_nm); rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_out+dmn_idx); } /* !ps_id_tpl */ if(flg_grd_hyb_cameam) rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_ids_out+dmn_idx); /* 20190602: ECMWF IFS PS variable has degenerate vertical dimension (lev_2). Avoid re-definition */ if(flg_grd_hyb_ecmwf) if(strcmp(dmn_nm,ilev_nm_out)) if(strcmp(dmn_nm,lev_nm_out)) rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_ids_out+dmn_idx); } /* !dmn_idx */ } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ rcd=nco_def_dim(out_id,lev_nm_out,lev_nbr_out,&dmn_id_lev_out); } /* !flg_grd_out_prs */ /* Do not extract grid variables (that are also extensive variables) like ilev, lev, hyai, hyam, hybi, hybm */ /* Exception list source: CAM: hyai, hyam, hybi, hybm, ilev, lev, P0, PS EAM: hyai, hyam, hybi, hybm, ilev, lev, P0, PS ECMWF: hyai, hyam, hybi, hybm, lev, lnsp NCEP: plev */ const int var_xcl_lst_nbr=10; /* [nbr] Number of objects on exclusion list */ const char *var_xcl_lst[]={"/hyai","/hyam","/hybi","/hybm","/ilev","/lev","/P0","/plev","/PS","/lnsp"}; int var_cpy_nbr=0; /* [nbr] Number of copied variables */ int var_rgr_nbr=0; /* [nbr] Number of regridded variables */ int var_xcl_nbr=0; /* [nbr] Number of deleted variables */ int var_crt_nbr=0; /* [nbr] Number of created variables */ long idx; /* [idx] Generic index */ unsigned int idx_tbl; /* [idx] Counter for traversal table */ const unsigned int trv_nbr=trv_tbl->nbr; /* [idx] Number of traversal table entries */ for(idx=0;idx<var_xcl_lst_nbr;idx++){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm_fll,var_xcl_lst[idx])) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* !idx_tbl */ } /* !idx */ /* 20191001: Do not automatically define plev_nm_in in pressure-grid output files The variable named lev_nm_out in the input data file is always defined in the output file So if plev_nm_in == lev_nm_out it will be defined anyway */ if(flg_grd_in_prs && flg_grd_out_prs && strcmp(plev_nm_in,lev_nm_out)){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm,plev_nm_in)) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* !idx_tbl */ } /* !idx */ char *var_nm; /* [sng] Variable name */ int *dmn_id_in=NULL; /* [id] Dimension IDs */ int *dmn_id_out=NULL; /* [id] Dimension IDs */ int var_id_in; /* [id] Variable ID */ int var_id_out; /* [id] Variable ID */ nc_type var_typ_out; /* [enm] Variable type to write to disk */ nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes "scale_factor", "add_offset" */ int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; dfl_lvl=rgr->dfl_lvl; fl_out_fmt=rgr->fl_out_fmt; /* Define new coordinates and grid variables in regridded file */ const int dmn_nbr_0D=0; /* [nbr] Rank of 0-D grid variables (scalars) */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ //const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ //const int dmn_nbr_3D=3; /* [nbr] Rank of 3-D grid variables */ //const int dmn_nbr_grd_max=dmn_nbr_3D; /* [nbr] Maximum rank of grid variables */ if(flg_grd_out_hyb){ rcd+=nco_def_var(out_id,"hyai",crd_typ_out,dmn_nbr_1D,&dmn_id_ilev_out,&hyai_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hyai_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"hyam",crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&hyam_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hyam_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"hybi",crd_typ_out,dmn_nbr_1D,&dmn_id_ilev_out,&hybi_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hybi_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"hybm",crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&hybm_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,hybm_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,ilev_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_ilev_out,&ilev_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ilev_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lev_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&lev_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lev_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,"P0",crd_typ_out,dmn_nbr_0D,(int *)NULL,&p0_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,p0_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; // for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ // rcd=nco_inq_dimname(out_id,dmn_ids_out[dmn_idx],dmn_nm); // (void)fprintf(stdout,"%s: DEBUG quark5 dmn_nbr_out = %d, dmn_nbr_ps = %d, dmn_idx = %d, dmn_ids_out[%d] = %d, dmn_nm = %s\n",nco_prg_nm_get(),dmn_nbr_out,dmn_nbr_ps,dmn_idx,dmn_idx,dmn_ids_out[dmn_idx],dmn_nm); // } /* !dmn_idx */ if(flg_grd_hyb_cameam) rcd+=nco_def_var(out_id,"PS",crd_typ_out,dmn_nbr_ps,dmn_ids_out,&ps_id); if(flg_grd_hyb_ecmwf){ /* Remove degenerate ECMWF vertical dimension so that output PS has dmn_nbr_ps-1 not dmn_nbr_ps dimensions */ int dmn_nbr_out_ecmwf=0; for(dmn_idx=0;dmn_idx<dmn_nbr_ps;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_ids_in[dmn_idx],dmn_nm); if(strcmp(dmn_nm,ilev_nm_out) && strcmp(dmn_nm,lev_nm_out) && strcmp(dmn_nm,"lev_2")) rcd=nco_inq_dimid(out_id,dmn_nm,dmn_ids_out+dmn_nbr_out_ecmwf++); } /* !dmn_idx */ rcd+=nco_def_var(out_id,"PS",crd_typ_out,dmn_nbr_out_ecmwf,dmn_ids_out,&ps_id); } /* !flg_grd_hyb_ecmwf */ if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ps_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; (void)nco_att_cpy(tpl_id,out_id,hyai_id_tpl,hyai_id,PCK_ATT_CPY); (void)nco_att_cpy(tpl_id,out_id,hyam_id_tpl,hyam_id,PCK_ATT_CPY); (void)nco_att_cpy(tpl_id,out_id,hybi_id_tpl,hybi_id,PCK_ATT_CPY); (void)nco_att_cpy(tpl_id,out_id,hybm_id_tpl,hybm_id,PCK_ATT_CPY); if(p0_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,p0_id_tpl,p0_id,PCK_ATT_CPY); /* p0 not expected to be in ECMWF grids */ if(ilev_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,ilev_id_tpl,ilev_id,PCK_ATT_CPY); else if(ilev_id_in != NC_MIN_INT) (void)nco_att_cpy(in_id,out_id,ilev_id_in,ilev_id,PCK_ATT_CPY); if(lev_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,lev_id_tpl,lev_id,PCK_ATT_CPY); else if(lev_id_in != NC_MIN_INT) (void)nco_att_cpy(in_id,out_id,lev_id_in,lev_id,PCK_ATT_CPY); if(ps_id_tpl != NC_MIN_INT) (void)nco_att_cpy(tpl_id,out_id,ps_id_tpl,ps_id,PCK_ATT_CPY); else (void)nco_att_cpy(in_id,out_id,ps_id_in,ps_id,PCK_ATT_CPY); } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ rcd+=nco_def_var(out_id,lev_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lev_out,&lev_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lev_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; (void)nco_att_cpy(tpl_id,out_id,lev_id_tpl,lev_id,PCK_ATT_CPY); dmn_id_ilev_out=dmn_id_lev_out; } /* !flg_grd_out_prs */ /* No further access to template file, close it */ nco_close(tpl_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_tpl); char *dmn_nm_cp; /* [sng] Dimension name as char * to reduce indirection */ nco_bool has_ilev; /* [flg] Contains interface level dimension */ nco_bool has_lev; /* [flg] Contains midpoint level dimension */ nco_bool has_tm; /* [flg] Contains time dimension */ nco_bool need_prs_ntf=False; /* [flg] At least one variable to regrid is on interface levels */ nco_bool need_prs_mdp=False; /* [flg] At least one variable to regrid is on midpoint levels */ trv_sct trv; /* [sct] Traversal table object structure to reduce indirection */ /* Define regridding flag for each variable */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ dmn_nbr_in=trv_tbl->lst[idx_tbl].nbr_dmn; has_ilev=False; has_lev=False; for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ /* Pre-determine flags necessary during next loop */ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; /* fxm: Generalize to include any variable containing coordinates with "standard_name" = "atmosphere_hybrid_sigma_pressure_coordinate" */ if(!has_ilev && ilev_nm_in) has_ilev=!strcmp(dmn_nm_cp,ilev_nm_in); if(!has_lev) has_lev=!strcmp(dmn_nm_cp,lev_nm_in); } /* end loop over dimensions */ /* Regrid variables that contain either vertical dimension */ if(has_ilev || has_lev){ trv_tbl->lst[idx_tbl].flg_rgr=True; var_rgr_nbr++; if(has_ilev) need_prs_ntf=True; if(has_lev) need_prs_mdp=True; } /* endif */ assert(!(has_ilev && has_lev)); /* Copy all variables that are not regridded or omitted */ if(!trv_tbl->lst[idx_tbl].flg_rgr) var_cpy_nbr++; } /* end nco_obj_typ_var */ } /* end idx_tbl */ if(!var_rgr_nbr) (void)fprintf(stdout,"%s: WARNING %s reports no variables fit interpolation criteria. The vertical interpolator expects something to interpolate, and variables not interpolated are copied straight to output. HINT: If the name(s) of the input vertical grid dimensions (e.g., ilev and lev) do not match NCO's preset defaults (case-insensitive unambiguous forms and abbreviations of \"ilev\", \"lev\", and/or \"plev\", respectively) then change the dimension names that NCO looks for. Instructions are at http://nco.sf.net/nco.html#regrid. For hybrid-pressure coordinate grids, ensure that the \"ilev\" and \"lev\" variable names are known with, e.g., \"ncks --rgr ilev_nm=interface_level --rgr lev_nm=midpoint_level\" or \"ncremap -R '--rgr ilev=interface_level --rgr lev=midpoint_level'\". For pure pressure grids, ensure the \"plev\" coordinate name is defined with, e.g., \"ncks --rgr plev_nm=pressure_level\" or \"ncremap -R '--rgr plev=pressure_level'\".\n",nco_prg_nm_get(),fnc_nm); if(nco_dbg_lvl_get() >= nco_dbg_fl){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr) (void)fprintf(stderr,"Interpolate %s? %s\n",trv.nm,trv.flg_rgr ? "Yes" : "No"); } /* end idx_tbl */ } /* end dbg */ /* Pre-allocate dimension ID and cnt/srt space */ int dmn_nbr_max; /* [nbr] Maximum number of dimensions variable can have in input or output */ rcd+=nco_inq_ndims(in_id,&dmn_nbr_max); dmn_id_in=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); aed_sct aed_mtd_fll_val; char *att_nm_fll_val=strdup("_FillValue"); int flg_pck; /* [flg] Variable is packed on disk */ nco_bool has_mss_val; /* [flg] Has numeric missing value attribute */ double mss_val_dbl; double mss_val_cmp_dbl; /* Missing value for comparison to double precision values */ float mss_val_flt; if(flg_add_msv_att){ aed_mtd_fll_val.att_nm=att_nm_fll_val; aed_mtd_fll_val.mode=aed_create; aed_mtd_fll_val.sz=1L; mss_val_dbl=NC_FILL_DOUBLE; mss_val_flt=NC_FILL_FLOAT; } /* !flg_add_msv_att */ /* Define interpolated and copied variables in output file */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ var_nm=trv.nm; /* Preserve input type in output type */ var_typ_out=trv.var_typ; dmn_nbr_in=trv.nbr_dmn; dmn_nbr_out=trv.nbr_dmn; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid_flg(out_id,var_nm,&var_id_out); /* If variable has not been defined, define it */ if(rcd != NC_NOERR){ if(trv.flg_rgr){ /* Interpolate */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); rcd=nco_inq_var_packing(in_id,var_id_in,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports variable \"%s\" is packed so results unpredictable. HINT: If regridded values seems weird, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,var_nm); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); if(ilev_nm_in && !strcmp(dmn_nm,ilev_nm_in)){ /* Change ilev dimension */ dmn_id_out[dmn_idx]=dmn_id_ilev_out; dmn_cnt_out[dmn_idx]=ilev_nbr_out; }else if(!strcmp(dmn_nm,lev_nm_in)){ /* Change lev dimension */ dmn_id_out[dmn_idx]=dmn_id_lev_out; dmn_cnt_out[dmn_idx]=lev_nbr_out; }else{ /* Dimensions ilev/lev_nm_in have already been defined as ilev/lev_nm_out, replicate all other dimensions */ rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx); } /* !ilev */ if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_out+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt_out[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_id_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ }else{ /* !flg_rgr */ /* Replicate non-interpolated variables */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_out+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt_out[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_id_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ } /* !flg_rgr */ rcd=nco_def_var(out_id,var_nm,var_typ_out,dmn_nbr_out,dmn_id_out,&var_id_out); /* Duplicate netCDF4 settings when possible */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC){ /* Deflation */ if(dmn_nbr_out > 0){ int dfl_lvl_in; /* [enm] Deflate level [0..9] */ rcd=nco_inq_var_deflate(in_id,var_id_in,&shuffle,&deflate,&dfl_lvl_in); /* Before netCDF 4.8.0, nco_def_var_deflate() could be called multiple times Properties of final invocation before nc_enddef() would take effect After netCDF 4.8.0 first instance of nco_def_var_deflate() takes effect */ if((deflate || shuffle) && dfl_lvl < 0){ /* Copy original filters if user did not explicity set dfl_lvl for output */ (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl_in); }else if(dfl_lvl >= 0){ /* Overwrite HDF Lempel-Ziv compression level, if requested */ deflate=(int)True; /* Turn-off shuffle when uncompressing otherwise chunking requests may fail */ if(dfl_lvl <= 0) shuffle=NC_NOSHUFFLE; /* Shuffle never, to my knowledge, increases filesize, so shuffle by default when manually deflating (and do not shuffle when uncompressing) */ if(dfl_lvl > 0) shuffle=NC_SHUFFLE; (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl); } /* !dfl_lvl */ } /* !dmn_nbr_out */ } /* !NC_FORMAT_NETCDF4 */ (void)nco_att_cpy(in_id,out_id,var_id_in,var_id_out,PCK_ATT_CPY); /* Variables with subterranean levels and missing-value extrapolation must have _FillValue attribute */ if(flg_add_msv_att && trv.flg_rgr){ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); if(!has_mss_val){ nco_bool flg_att_chg; /* [flg] _FillValue attribute was written */ aed_mtd_fll_val.var_nm=var_nm; aed_mtd_fll_val.id=var_id_out; aed_mtd_fll_val.type=var_typ_out; if(var_typ_out == NC_FLOAT) aed_mtd_fll_val.val.fp=&mss_val_flt; else if(var_typ_out == NC_DOUBLE) aed_mtd_fll_val.val.dp=&mss_val_dbl; flg_att_chg=nco_aed_prc(out_id,var_id_out,aed_mtd_fll_val); if(!flg_att_chg && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: WARNING %s reports unsuccessful attempt to create _FillValue attribute for variable %s\n",nco_prg_nm_get(),fnc_nm,var_nm); } /* !has_mss_val */ } /* !flg_add_msv_att */ } /* !rcd */ } /* !var */ } /* !idx_tbl */ /* Free pre-allocated array space */ if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Begin data mode */ (void)nco_enddef(out_id); /* Copy all grid variables */ if(flg_grd_out_hyb){ (void)nco_put_var(out_id,hyai_id,hyai_out,crd_typ_out); (void)nco_put_var(out_id,hyam_id,hyam_out,crd_typ_out); (void)nco_put_var(out_id,hybi_id,hybi_out,crd_typ_out); (void)nco_put_var(out_id,hybm_id,hybm_out,crd_typ_out); (void)nco_put_var(out_id,ilev_id,ilev_out,crd_typ_out); (void)nco_put_var(out_id,lev_id,lev_out,crd_typ_out); (void)nco_put_var(out_id,p0_id,&p0_out,crd_typ_out); (void)nco_put_var(out_id,ps_id,ps_out,crd_typ_out); } /* !flg_grd_out_hyb */ if(flg_grd_out_prs){ (void)nco_put_var(out_id,lev_id,lev_out,crd_typ_out); } /* !flg_grd_out_prs */ nco_bool flg_ntp_log=True; /* [flg] Interpolate in log(vertical_coordinate) */ if(ntp_mth == nco_ntp_lnr) flg_ntp_log=False; size_t idx_in; /* [idx] Index into 3D input variables */ size_t idx_out; /* [idx] Index into 3D output variables */ size_t var_sz_in; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t var_sz_out; /* [nbr] Number of elements in variable (will be self-multiplied) */ /* Interpolate or copy variable values */ double *var_val_dbl_in=NULL; double *var_val_dbl_out=NULL; double *prs_ntp_in; /* [Pa] Interpolated pressure array on input grid */ double *prs_ntp_out; /* [Pa] Interpolated pressure array on output grid */ int lvl_idx_in; /* [idx] Level index on input grid */ int lvl_idx_out; /* [idx] Level index on output grid */ int lvl_nbr_in; /* [nbr] Number of levels for current interpolated variable on input grid */ int lvl_nbr_out; /* [nbr] Number of levels for current interpolated variable on output grid */ int thr_idx; /* [idx] Thread index */ size_t grd_nbr=grd_sz_in; /* [nbr] Horizonal grid size */ size_t idx_dbg=rgr->idx_dbg; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped as shared in parallel clause */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ /* Repeating above documentation for the forgetful: NB: tm_nbr is max(timesteps) in vertical grid definitions, not number of records in either file This implementation interpolates timeseries to/from time-invariant vertical grids in one OpenMP call! */ for(tm_idx=0;tm_idx<tm_nbr;tm_idx++){ /* Index-offset to current surface pressure timeslice */ idx_fst=tm_idx*grd_sz_in; if(need_prs_mdp){ /* Allocated and define midpoint pressures */ if(tm_idx == 0) prs_mdp_in=(double *)nco_malloc_dbg(grd_sz_in*lev_nbr_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_mdp_in value buffer"); if(tm_idx == 0) prs_mdp_out=(double *)nco_malloc_dbg(grd_sz_out*lev_nbr_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_mdp_out value buffer"); if(flg_grd_in_hyb) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_in;lev_idx++) prs_mdp_in[grd_idx+lev_idx*grd_sz_in]=p0_in*hyam_in[lev_idx]+ps_in[idx_fst+grd_idx]*hybm_in[lev_idx]; if(flg_grd_out_hyb) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_out;lev_idx++) prs_mdp_out[grd_idx+lev_idx*grd_sz_out]=p0_out*hyam_out[lev_idx]+ps_out[idx_fst+grd_idx]*hybm_out[lev_idx]; if(flg_grd_in_prs) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_in;lev_idx++) prs_mdp_in[grd_idx+lev_idx*grd_sz_in]=lev_in[lev_idx]; if(flg_grd_out_prs) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(lev_idx=0;lev_idx<lev_nbr_out;lev_idx++) prs_mdp_out[grd_idx+lev_idx*grd_sz_out]=lev_out[lev_idx]; if(flg_ntp_log){ var_sz_in=grd_sz_in*lev_nbr_in; for(idx_in=0;idx_in<var_sz_in;idx_in++) prs_mdp_in[idx_in]=log(prs_mdp_in[idx_in]); var_sz_out=grd_sz_out*lev_nbr_out; for(idx_out=0;idx_out<var_sz_out;idx_out++) prs_mdp_out[idx_out]=log(prs_mdp_out[idx_out]); } /* !flg_ntp_log */ } /* !need_prs_mdp */ if(need_prs_ntf){ /* Allocate and define interface pressures */ if(tm_idx == 0) prs_ntf_in=(double *)nco_malloc_dbg(grd_sz_in*ilev_nbr_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_ntf_in value buffer"); if(tm_idx == 0) prs_ntf_out=(double *)nco_malloc_dbg(grd_sz_out*ilev_nbr_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() prs_ntf_out value buffer"); if(flg_grd_in_hyb) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_in;ilev_idx++) prs_ntf_in[grd_idx+ilev_idx*grd_sz_in]=p0_in*hyai_in[ilev_idx]+ps_in[idx_fst+grd_idx]*hybi_in[ilev_idx]; if(flg_grd_out_hyb) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_out;ilev_idx++) prs_ntf_out[grd_idx+ilev_idx*grd_sz_out]=p0_out*hyai_out[ilev_idx]+ps_out[idx_fst+grd_idx]*hybi_out[ilev_idx]; if(flg_grd_in_prs) for(grd_idx=0;grd_idx<grd_sz_in;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_in;ilev_idx++) prs_ntf_in[grd_idx+ilev_idx*grd_sz_in]=lev_in[ilev_idx]; if(flg_grd_out_prs) for(grd_idx=0;grd_idx<grd_sz_out;grd_idx++) for(ilev_idx=0;ilev_idx<ilev_nbr_out;ilev_idx++) prs_ntf_out[grd_idx+ilev_idx*grd_sz_out]=lev_out[ilev_idx]; if(flg_ntp_log){ var_sz_in=grd_sz_in*ilev_nbr_in; for(idx_in=0;idx_in<var_sz_in;idx_in++) prs_ntf_in[idx_in]=log(prs_ntf_in[idx_in]); var_sz_out=grd_sz_out*ilev_nbr_out; for(idx_out=0;idx_out<var_sz_out;idx_out++) prs_ntf_out[idx_out]=log(prs_ntf_out[idx_out]); } /* !flg_ntp_log */ } /* !need_prs_ntf */ /* Set firstprivate variables to initial values */ has_ilev=False; has_lev=False; has_tm=False; if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"Interpolation progress: # means interpolated, ~ means copied\n"); #ifdef __GNUG__ # define GCC_LIB_VERSION ( __GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__ ) # if GCC_LIB_VERSION < 490 # define GXX_OLD_OPENMP_SHARED_TREATMENT 1 # endif /* 480 */ # if GCC_LIB_VERSION >= 900 # define GXX_WITH_OPENMP5_GPU_SUPPORT 1 # endif /* 900 */ #endif /* !__GNUC__ */ #if defined( __INTEL_COMPILER) # pragma omp parallel for default(none) firstprivate(has_ilev,has_lev,has_tm,var_val_dbl_in,var_val_dbl_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_cmp_dbl,mss_val_dbl,prs_ntp_in,prs_ntp_out,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_ilev_in,dmn_id_ilev_out,dmn_id_lev_in,dmn_id_lev_out,dmn_id_tm_in,flg_ntp_log,flg_vrt_tm,fnc_nm,grd_nbr,idx_dbg,ilev_nbr_in,ilev_nbr_out,lev_nbr_in,lev_nbr_out,out_id,prs_mdp_in,prs_mdp_out,prs_ntf_in,prs_ntf_out,tm_idx,xtr_mth) #else /* !__INTEL_COMPILER */ # ifdef GXX_OLD_OPENMP_SHARED_TREATMENT # pragma omp parallel for default(none) firstprivate(has_ilev,has_lev,has_tm,var_val_dbl_in,var_val_dbl_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_cmp_dbl,mss_val_dbl,prs_ntp_in,prs_ntp_out,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_ilev_in,dmn_id_ilev_out,dmn_id_lev_in,dmn_id_lev_out,dmn_id_tm_in,flg_ntp_log,flg_vrt_tm,fnc_nm,grd_nbr,idx_dbg,ilev_nbr_in,ilev_nbr_out,lev_nbr_in,lev_nbr_out,out_id,prs_mdp_in,prs_mdp_out,prs_ntf_in,prs_ntf_out,tm_idx,xtr_mth) # else /* !old g++ */ # if defined(GXX_WITH_OPENMP5_GPU_SUPPORT) && 0 # pragma omp target teams distribute parallel for # else # pragma omp parallel for firstprivate(has_ilev,has_lev,has_tm,var_val_dbl_in,var_val_dbl_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_cmp_dbl,mss_val_dbl,prs_ntp_in,prs_ntp_out,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_ilev_in,dmn_id_ilev_out,dmn_id_lev_in,dmn_id_lev_out,dmn_id_tm_in,flg_ntp_log,flg_vrt_tm,grd_nbr,idx_dbg,ilev_nbr_in,ilev_nbr_out,lev_nbr_in,lev_nbr_out,out_id,prs_mdp_in,prs_mdp_out,prs_ntf_in,prs_ntf_out,tm_idx,xtr_mth) # endif /* !GCC > 9.0 */ # endif /* !GCC < 4.9 */ #endif /* !__INTEL_COMPILER */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; thr_idx=omp_get_thread_num(); in_id=trv_tbl->in_id_arr[thr_idx]; #ifdef _OPENMP if(nco_dbg_lvl_get() >= nco_dbg_grp && !thr_idx && !idx_tbl) (void)fprintf(fp_stdout,"%s: INFO %s reports regrid loop uses %d thread%s\n",nco_prg_nm_get(),fnc_nm,omp_get_num_threads(),(omp_get_num_threads() > 1) ? "s" : ""); if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO thread = %d, idx_tbl = %d, nm = %s\n",nco_prg_nm_get(),thr_idx,idx_tbl,trv.nm); #endif /* !_OPENMP */ if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s%s ",trv.flg_rgr ? "#" : "~",trv.nm); if(trv.flg_rgr){ /* Interpolate variable */ var_nm=trv.nm; if(!strcmp(var_nm,"US") || !strcmp(var_nm,"VS")) (void)fprintf(fp_stdout,"%s: WARNING %s reports attempt to vertically interpolate a variable named \"%s\". If this variable is from a CESM CAM or E3SM EAM output or initial condition file on a rectangular grid (e.g., FV 0.9x1.25), then expect this program to fail and dump core when interpolating US and to produce slightly incorrect answers for VS. The vertical interpolation routine requires that interpolated variables be on the same horizontal grid as the supplied pressure field. However, the CAM/EAM US and VS variables from rectangular grid simulations are often on a horizontal grid, called the staggered grid, that is offset from the rest of the variables including the surface pressure. US usually sits on a grid that is staggered in latitude from, and is a slightly different size than, the surface pressure grid. This leads to a core dump. VS sits on a grid staggered in longitude from, though the same size as, the surface pressure field. The resulting interpolation will be based on surface pressure half a gridcell to the east rather than centered with VS. The correct procedure to vertically interpolate US and VS is to 1) horizontally regrid the supplied surface pressure (often \"PS\") to the staggered grid, then 2) vertically interpolate US and VS to the desired vertical grid based on the surface pressure on the staggered grid, then 3) re-combine the interpolated US and VS with the interpolated versions of the rest of the variables. The best solution to this dilemma is to script this workflow. Contact Charlie if you need help with this.\n",nco_prg_nm_get(),fnc_nm,var_nm); var_typ_rgr=NC_DOUBLE; /* NB: Perform regridding in double precision */ var_typ_out=trv.var_typ; /* NB: Output type in file is same as input type */ var_sz_in=1L; var_sz_out=1L; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid(out_id,var_nm,&var_id_out); rcd=nco_inq_varndims(in_id,var_id_in,&dmn_nbr_in); rcd=nco_inq_varndims(out_id,var_id_out,&dmn_nbr_out); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_id_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); rcd=nco_inq_vardimid(out_id,var_id_out,dmn_id_out); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_in+dmn_idx); if(dmn_id_in[dmn_idx] == dmn_id_ilev_in) has_ilev=True; if(dmn_id_in[dmn_idx] == dmn_id_lev_in) has_lev=True; if(dmn_id_in[dmn_idx] == dmn_id_tm_in) has_tm=True; if(flg_vrt_tm && has_tm && dmn_id_in[dmn_idx] == dmn_id_tm_in){ dmn_cnt_in[dmn_idx]=1L; dmn_srt[dmn_idx]=tm_idx; }else{ dmn_srt[dmn_idx]=0L; } /* !flg_vrt_tm */ var_sz_in*=dmn_cnt_in[dmn_idx]; } /* !dmn_idx */ var_val_dbl_in=(double *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() input value buffer"); rcd=nco_get_vara(in_id,var_id_in,dmn_srt,dmn_cnt_in,var_val_dbl_in,var_typ_rgr); for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ /* Dimension count vector is same as input except for lvl dimension */ dmn_cnt_out[dmn_idx]=dmn_cnt_in[dmn_idx]; if(has_ilev && dmn_id_out[dmn_idx] == dmn_id_ilev_out) dmn_cnt_out[dmn_idx]=ilev_nbr_out; if(has_lev && dmn_id_out[dmn_idx] == dmn_id_lev_out) dmn_cnt_out[dmn_idx]=lev_nbr_out; var_sz_out*=dmn_cnt_out[dmn_idx]; } /* !dmn_idx */ var_val_dbl_out=(double *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() output value buffer"); /* Missing value setup */ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); if(has_mss_val) mss_val_cmp_dbl=mss_val_dbl; else mss_val_cmp_dbl=NC_FILL_DOUBLE; if(has_ilev){ /* Interpolate current variable from input interface pressure grid to output interface pressure grid */ lvl_nbr_in=ilev_nbr_in; lvl_nbr_out=ilev_nbr_out; prs_ntp_in=prs_ntf_in; prs_ntp_out=prs_ntf_out; }else{ /* Interpolate current variable from input midpoint pressure grid to output midpoint pressure grid */ lvl_nbr_in=lev_nbr_in; lvl_nbr_out=lev_nbr_out; prs_ntp_in=prs_mdp_in; prs_ntp_out=prs_mdp_out; } /* !ilev */ /* Procedure: Extract input/output coordinate/data arrays into 1D column order This enables actual interpolation code to be written for, or take advantage of, 1D interpolation routines After interpolating into 1D sequential memory, copy back to ND output and repeat */ double *crd_in=NULL; /* Input vertical coordinate (must be monotonic) */ double *crd_out=NULL; /* Output vertical coordinate (must be monotonic) */ double *dat_in=NULL; /* Input data (to be interpolated) on input vertical coordinate grid */ double *dat_out=NULL; /* Output data (interpolated) output vertical coordinate grid (i.e., the answer) */ double *crd_in_mnt; /* Input vertical coordinate reversed if necessary to be monotonically increasing */ double *crd_out_mnt; /* Output vertical coordinate reversed if necessary to be monotonically increasing */ double *dat_in_mnt; /* Input data (to be interpolated) reversed if necessary along with input grid */ double *dat_out_mnt; /* Output data (interpolated) reversed if necessary along with output grid */ nco_xtr_sct xtr_LHS; nco_xtr_sct xtr_RHS; size_t brk_lft_idx; size_t brk_rgt_idx; size_t in_idx; size_t in_nbr; size_t out_nbr; size_t out_idx; /* Default extrapolation uses nearest valid neighbor */ xtr_LHS.xtr_fll=True; xtr_LHS.xtr_vrb=False; xtr_LHS.typ_fll=xtr_mth; xtr_RHS.xtr_fll=True; xtr_RHS.xtr_vrb=False; xtr_RHS.typ_fll=xtr_mth; /* Special-case extrapolation methods allowed for all except missing-value extrapolation types */ if(xtr_mth != nco_xtr_fll_msv){ if(!strcmp(var_nm,"T") || !strcmp(var_nm,"ta")) xtr_RHS.typ_fll=nco_xtr_fll_tpt; else if(!strcmp(var_nm,"Z3") || !strcmp(var_nm,"zg")) xtr_LHS.typ_fll=xtr_RHS.typ_fll=nco_xtr_fll_gph; } /* !xtr_mth */ crd_in=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); crd_out=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); dat_in=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); dat_out=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); in_nbr=lvl_nbr_in; out_nbr=lvl_nbr_out; nco_bool in_ncr; /* [flg] Input coordinate monotonically increases */ nco_bool out_ncr; /* [flg] Output coordinate monotonically increases */ /* Determine monotonicity direction only once, based on first vertical column */ if(prs_ntp_in[grd_nbr]-prs_ntp_in[0] > 0.0) in_ncr=True; else in_ncr=False; out_ncr=True; if(out_nbr > 1) if(prs_ntp_out[grd_nbr]-prs_ntp_out[0] < 0.0) out_ncr=False; /* If necessary, allocate (once, and re-use it) additional memory to hold reversed arrays */ if(!in_ncr){ crd_in_mnt=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); dat_in_mnt=(double *)nco_malloc(lvl_nbr_in*sizeof(double)); } /* !in_ncr */ if(!out_ncr){ crd_out_mnt=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); dat_out_mnt=(double *)nco_malloc(lvl_nbr_out*sizeof(double)); } /* !out_ncr */ /* Constants and parameters for extrapolation */ const double gamma_moist=6.5/10000.0; /* [K/Pa] Temperature extrapolation assumes constant moist adiabatic lower atmosphere lapse rate dT/dp=constant=(6.5 K)/(100 mb) = (6.5 K)/(10000 Pa) */ const double Rd_rcp_g0=287.0/9.81; /* [K/Pa] Geopotential height extrapolation uses hypsometric equation Z2-Z1=(Rd*Tv_avg/g0)*ln(p1/p2)=(Rd*Tv_avg/g0)*(ln(p1)-ln(p2)) */ const double tpt_vrt_avg=288.0; /* [K] Mean virtual temperature assumed for geopotential height extrapolation */ nco_bool FIRST_WARNING_LHS; /* [flg] First warning for LHS extrapolation */ nco_bool FIRST_WARNING_RHS; /* [flg] First warning for RHS extrapolation */ if(tm_idx == 0){ /* Only print extrapolation warnings for first timestep to prevent noisy output NB: Algorithm prevents any warnings for extrapolations that appear after first timestep */ FIRST_WARNING_LHS=True; FIRST_WARNING_RHS=True; } /* !tm_idx */ /* Outer loop over columns */ for(grd_idx=0;grd_idx<grd_nbr;grd_idx++){ /* Initialize pseudo-1D variables with consecutive memory addresses to avoid indirection */ for(lvl_idx_in=0;lvl_idx_in<lvl_nbr_in;lvl_idx_in++){ idx_in=grd_idx+lvl_idx_in*grd_nbr; crd_in[lvl_idx_in]=prs_ntp_in[idx_in]; dat_in[lvl_idx_in]=var_val_dbl_in[idx_in]; } /* !lvl_idx_in */ for(lvl_idx_out=0;lvl_idx_out<lvl_nbr_out;lvl_idx_out++){ idx_out=grd_idx+lvl_idx_out*grd_nbr; crd_out[lvl_idx_out]=prs_ntp_out[idx_out]; } /* !lvl_idx_out */ /* Interpolation code easier to write/debug if crd_in and crd_out both monotonically increase However, monotonically decreasing coordinates useful in many cases, such as depth coordinate, and pressure levels arranged largest to smallest (favored by CMIP) Next code block reverses array(s) if necessary so coordinates monotonically increase Code uses crd_in_mnt, dat_in_mnt, crd_out_mnt where "_mnt" reminds of "monotonically increasing" assumption Following code lifted from CSZ's libcsz.a library source code ~/sw/c++/vec.hh */ if(in_ncr){ crd_in_mnt=crd_in; dat_in_mnt=dat_in; }else{ for(in_idx=0;in_idx<in_nbr;in_idx++){ crd_in_mnt[in_idx]=crd_in[in_nbr-in_idx-1]; dat_in_mnt[in_idx]=dat_in[in_nbr-in_idx-1]; } /* !in_idx */ } /* !in_ncr */ if(out_ncr){ crd_out_mnt=crd_out; dat_out_mnt=dat_out; }else{ for(out_idx=0;out_idx<out_nbr;out_idx++) crd_out_mnt[out_idx]=crd_out[out_nbr-out_idx-1]; } /* !out_ncr */ // Initialize bracketing index brk_lft_idx=0; // Loop over desired output coordinates for(out_idx=0;out_idx<out_nbr;out_idx++){ // Order of conditions is important since second condition is illegal if brk_lft_idx >= in_nbr while((brk_lft_idx < in_nbr) && (crd_in_mnt[brk_lft_idx] < crd_out_mnt[out_idx])){ brk_lft_idx++; } // !while brk_lft_idx--; // Handle identity interpolation separately to preserve symmetry in extrapolation code if(brk_lft_idx != in_nbr-1){ if(crd_in_mnt[brk_lft_idx+1] == crd_out_mnt[out_idx]){ dat_out_mnt[out_idx]=dat_in_mnt[brk_lft_idx+1]; if(brk_lft_idx == -1) brk_lft_idx=0; // Reset brk_lft_idx to 0 so next while loop works continue; // Jump to next iteration } // !crd_in_mnt } // !brk_lft_idx if(brk_lft_idx == -1){ // LHS Extrapolation required // Degenerate case: crd_out_mnt[out_idx] < crd_in_mnt[0] brk_lft_idx=0; // Reset brk_lft_idx to 0 so next while loop works if(xtr_LHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: WARNING %s reports variable %s column %lu output value dat_out_mnt[%lu] at coordinate crd_out_mnt[%lu] = %g requires LHS extrapolation beyond leftmost valid coordinate at crd_in_mnt[%lu] = %g. Nearest valid datum is dat_in_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,var_nm,grd_idx,out_idx,out_idx,crd_out_mnt[out_idx],brk_lft_idx,crd_in_mnt[brk_lft_idx],brk_lft_idx,dat_in_mnt[brk_lft_idx]); // Extrapolation options are presented in decreasing order of preference if(!xtr_LHS.xtr_fll){ (void)fprintf(fp_stdout,"%s: ERROR %s Full LHS extrapolation required but not permitted\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; } /* !xtr_LHS.xtr_fll */ switch(xtr_LHS.typ_fll){ case nco_xtr_fll_nil: dat_out_mnt[out_idx]=0.0; break; case nco_xtr_fll_msv: dat_out_mnt[out_idx]=mss_val_cmp_dbl; break; case nco_xtr_fll_ngh: dat_out_mnt[out_idx]=dat_in_mnt[0]; break; case nco_xtr_fll_lnr: dat_out_mnt[out_idx]=dat_in_mnt[0]- (crd_in_mnt[0]-crd_out_mnt[out_idx])* (dat_in_mnt[1]-dat_in_mnt[0])/(crd_in_mnt[1]-crd_in_mnt[0]); break; case nco_xtr_fll_gph: if(flg_ntp_log) /* Coordinates are already logarithmic in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[0]+ Rd_rcp_g0*tpt_vrt_avg*(crd_in_mnt[0]-crd_out_mnt[out_idx]); else /* Interpolate with logarithm of pressure coordinates */ dat_out_mnt[out_idx]=dat_in_mnt[0]+ Rd_rcp_g0*tpt_vrt_avg*log(crd_in_mnt[0]/crd_out_mnt[out_idx]); if(FIRST_WARNING_LHS) (void)fprintf(fp_stdout,"%s: INFO %s geopotential height extrapolated upward towards space using hypsometric equation with constant global mean virtual temperature = %g for variable %s\n",nco_prg_nm_get(),fnc_nm,tpt_vrt_avg,var_nm); FIRST_WARNING_LHS=False; break; default: (void)fprintf(fp_stdout,"%s: ERROR %s Unknown xtr_LHS.typ_fll\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; break; } // !xtr_LHS.typ_fll if(xtr_LHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: INFO %s LHS extrapolation yields dat_out_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,out_idx,dat_out_mnt[out_idx]); }else if(brk_lft_idx < in_nbr-1){ // Normal case: crd_out_mnt is interpolable brk_rgt_idx=brk_lft_idx+1; // NB: brk_rgt_idx is ALWAYS greater than brk_lft_idx // This simulaneously meets two criteria: // 1. Divide-by-zero errors are impossible in the next step // 2. The identity interpolation is satisfied since crd_dlt == 0.0: // i.e., If crd_out_mnt[idx] == crd_in_mnt[brk_lft_idx] then dat_out_mnt[out_idx] := dat_in_mnt[brk_lft_idx] // Linearly interpolate dat_out_mnt[out_idx]= dat_in_mnt[brk_lft_idx]+ (crd_out_mnt[out_idx]-crd_in_mnt[brk_lft_idx])* (dat_in_mnt[brk_rgt_idx]-dat_in_mnt[brk_lft_idx])/ (crd_in_mnt[brk_rgt_idx]-crd_in_mnt[brk_lft_idx]); }else if(brk_lft_idx == in_nbr-1){ // RHS Extrapolation required // Degenerate case: brk_lft_idx is last element of crd_in_mnt brk_rgt_idx=brk_lft_idx; if(xtr_RHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: WARNING %s reports variable %s column %lu output value dat_out_mnt[%lu] at coordinate crd_out_mnt[%lu] = %g requires RHS extrapolation beyond rightmost valid coordinate at crd_in_mnt[%lu] = %g. Nearest valid datum is dat_in_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,var_nm,grd_idx,out_idx,out_idx,crd_out_mnt[out_idx],brk_rgt_idx,crd_in_mnt[brk_rgt_idx],brk_rgt_idx,dat_in_mnt[brk_rgt_idx]); // Extrapolation options are presented in decreasing order of preference if(!xtr_RHS.xtr_fll){ (void)fprintf(fp_stdout,"%s: ERROR %s Full RHS extrapolation required but not permitted\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; } /* !xtr_RHS.xtr_fll */ switch(xtr_RHS.typ_fll){ case nco_xtr_fll_nil: dat_out_mnt[out_idx]=0.0; break; case nco_xtr_fll_msv: dat_out_mnt[out_idx]=mss_val_cmp_dbl; break; case nco_xtr_fll_ngh: dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]; break; case nco_xtr_fll_lnr: dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]+ (crd_out_mnt[out_idx]-crd_in_mnt[in_nbr-1])* (dat_in_mnt[in_nbr-1]-dat_in_mnt[in_nbr-2])/ (crd_in_mnt[in_nbr-1]-crd_in_mnt[in_nbr-2]); break; case nco_xtr_fll_tpt: if(flg_ntp_log) /* Exponentiate so coordinates are linear in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]+ (exp(crd_out_mnt[out_idx])-exp(crd_in_mnt[in_nbr-1]))*gamma_moist; else /* Coordinates are already linear in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]+ (crd_out_mnt[out_idx]-crd_in_mnt[in_nbr-1])*gamma_moist; if(FIRST_WARNING_RHS) (void)fprintf(fp_stdout,"%s: INFO %s temperature extrapolated toward/into surface assuming constant moist adiabatic lapse rate = %g K/(100 mb) for variable %s\n",nco_prg_nm_get(),fnc_nm,gamma_moist*10000.0,var_nm); FIRST_WARNING_RHS=False; break; case nco_xtr_fll_gph: if(flg_ntp_log) /* Coordinates are already logarithmic in pressure */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]- Rd_rcp_g0*tpt_vrt_avg*(crd_out_mnt[out_idx]-crd_in_mnt[in_nbr-1]); else /* Interpolate with logarithm of pressure coordinates */ dat_out_mnt[out_idx]=dat_in_mnt[in_nbr-1]- Rd_rcp_g0*tpt_vrt_avg*log(crd_out_mnt[out_idx]/crd_in_mnt[in_nbr-1]); if(FIRST_WARNING_RHS) (void)fprintf(fp_stdout,"%s: INFO %s geopotential height extrapolated toward/into surface using hypsometric equation with constant global mean virtual temperature = %g for variable %s\n",nco_prg_nm_get(),fnc_nm,tpt_vrt_avg,var_nm); FIRST_WARNING_RHS=False; break; default: (void)fprintf(fp_stdout,"%s: ERROR %s Unknown xtr_RHS\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; break; } // !xtr_RHS.typ_fll if(xtr_RHS.xtr_vrb) (void)fprintf(fp_stdout,"%s: INFO %s RHS extrapolation yields dat_out_mnt[%lu] = %g\n",nco_prg_nm_get(),fnc_nm,out_idx,dat_out_mnt[out_idx]); }else{ (void)fprintf(fp_stdout,"%s: ERROR %s Unforeseen value of brk_lft_idx\n",nco_prg_nm_get(),fnc_nm); // return NCO_ERR; } // !RHS } // !out_idx /* Un-reverse output data to be on original grid */ if(!out_ncr) for(out_idx=0;out_idx<out_nbr;out_idx++) dat_out[out_idx]=dat_out_mnt[out_nbr-out_idx-1]; // End of vec.hh code /* Copy answers into output array */ for(lvl_idx_out=0;lvl_idx_out<lvl_nbr_out;lvl_idx_out++){ idx_out=grd_idx+lvl_idx_out*grd_nbr; var_val_dbl_out[idx_out]=dat_out[lvl_idx_out]; } /* !lvl_idx_out */ if(nco_dbg_lvl_get() >= nco_dbg_io && grd_idx == idx_dbg){ (void)fprintf(fp_stdout,"%s: DEBUG %s variable %s at idx_dbg = %lu\n",nco_prg_nm_get(),fnc_nm,var_nm,idx_dbg); for(out_idx=0;out_idx<out_nbr;out_idx++){ (void)fprintf(fp_stdout,"out_idx = %lu dat_out = %g\n",out_idx,dat_out[out_idx]); } /* !out_idx */ } /* !dbg */ } /* !grd_idx */ if(crd_in) crd_in=(double *)nco_free(crd_in); if(crd_out) crd_out=(double *)nco_free(crd_out); if(dat_in) dat_in=(double *)nco_free(dat_in); if(dat_out) dat_out=(double *)nco_free(dat_out); if(!in_ncr){ if(crd_in_mnt) crd_in_mnt=(double *)nco_free(crd_in_mnt); if(dat_in_mnt) dat_in_mnt=(double *)nco_free(dat_in_mnt); } /* !in_ncr */ if(!out_ncr){ if(crd_out_mnt) crd_out_mnt=(double *)nco_free(crd_out_mnt); if(dat_out_mnt) dat_out_mnt=(double *)nco_free(dat_out_mnt); } /* !out_ncr */ if(nco_typ_ntg(var_typ_out)){ /* 20210407: Round, with rint(), integer fields before sending to netCDF for output Otherwise implicit type conversion will truncate (rather than round) output values This is critical for masks where rounding errors produce near integer values (e.g., 0.999...) that could then be truncated to zero by implicit conversion instead of rounded up to 1. */ for(idx_out=0;idx_out<var_sz_out;idx_out++) if(var_val_dbl_out[idx_out] != mss_val_cmp_dbl) var_val_dbl_out[idx_out]=rint(var_val_dbl_out[idx_out]); } /* !nco_typ_ntg() */ #pragma omp critical { /* begin OpenMP critical */ rcd=nco_put_vara(out_id,var_id_out,dmn_srt,dmn_cnt_out,var_val_dbl_out,var_typ_rgr); } /* end OpenMP critical */ if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(var_val_dbl_in) var_val_dbl_in=(double *)nco_free(var_val_dbl_in); if(var_val_dbl_out) var_val_dbl_out=(double *)nco_free(var_val_dbl_out); }else{ /* !trv.flg_rgr */ /* Use standard NCO copy routine for variables that are not regridded 20190511: Copy them only once */ if(tm_idx == 0){ #pragma omp critical { /* begin OpenMP critical */ (void)nco_cpy_var_val(in_id,out_id,(FILE *)NULL,(md5_sct *)NULL,trv.nm,trv_tbl); } /* end OpenMP critical */ } /* !tm_idx */ } /* !flg_rgr */ } /* !xtr */ } /* end (OpenMP parallel for) loop over idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"\n"); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s completion report: Variables interpolated = %d, copied unmodified = %d, omitted = %d, created = %d\n",nco_prg_nm_get(),fnc_nm,var_rgr_nbr,var_cpy_nbr,var_xcl_nbr,var_crt_nbr); } /* !tm_idx */ if(att_nm_fll_val) att_nm_fll_val=(char *)nco_free(att_nm_fll_val); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_ids_in) dmn_ids_in=(int *)nco_free(dmn_ids_in); if(dmn_ids_out) dmn_ids_out=(int *)nco_free(dmn_ids_out); if(ilev_nm_in) ilev_nm_in=(char *)nco_free(ilev_nm_in); if(lev_nm_in) lev_nm_in=(char *)nco_free(lev_nm_in); if(hyai_in) hyai_in=(double *)nco_free(hyai_in); if(hyam_in) hyam_in=(double *)nco_free(hyam_in); if(hybi_in) hybi_in=(double *)nco_free(hybi_in); if(hybm_in) hybm_in=(double *)nco_free(hybm_in); if(ps_in) ps_in=(double *)nco_free(ps_in); if(prs_mdp_in) prs_mdp_in=(double *)nco_free(prs_mdp_in); if(prs_ntf_in) prs_ntf_in=(double *)nco_free(prs_ntf_in); if(hyai_out) hyai_out=(double *)nco_free(hyai_out); if(hyam_out) hyam_out=(double *)nco_free(hyam_out); if(hybi_out) hybi_out=(double *)nco_free(hybi_out); if(hybm_out) hybm_out=(double *)nco_free(hybm_out); if(ilev_out) ilev_out=(double *)nco_free(ilev_out); if(lev_in) lev_in=(double *)nco_free(lev_in); if(lev_out) lev_out=(double *)nco_free(lev_out); if(ps_out) ps_out=(double *)nco_free(ps_out); if(prs_mdp_out) prs_mdp_out=(double *)nco_free(prs_mdp_out); if(prs_ntf_out) prs_ntf_out=(double *)nco_free(prs_ntf_out); return rcd; } /* !nco_ntp_vrt() */ int /* O [enm] Return code */ nco_rgr_wgt /* [fnc] Regrid with external weights */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Regrid fields using external weights contained in a mapfile Examine ESMF, SCRIP, Tempest map-files: ncks --cdl -M -m ${DATA}/scrip/rmp_T42_to_POP43_conserv.nc | m ncks --cdl -M -m ${DATA}/maps/map_t42_to_fv129x256_aave.20150621.nc | m ncks --cdl -M -m ${DATA}/maps/map_ne30np4_to_ne120np4_tps.20150618.nc | m Test ESMF, SCRIP, Tempest map-files: ncks -D 5 -O --map=${DATA}/scrip/rmp_T42_to_POP43_conserv.nc ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc ncks -D 5 -O --map=${DATA}/maps/map_t42_to_fv129x256_aave.20150621.nc ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc ncks -D 5 -O --map=${DATA}/maps/map_ne30np4_to_ne120np4_tps.20150618.nc ${DATA}/ne30/rgr/ne30_1D.nc ~/foo.nc Mapfile formats ESMF, GRIDSPEC, SCRIP, and UGRID described here: http://www.earthsystemmodeling.org/esmf_releases/public/ESMF_6_3_0rp1/ESMF_refdoc/node3.html#sec:fileformat:scrip Conventions: grid_size: Number of gridcells (product of lat*lon) address: Source and destination index for each link pair num_links: Number of unique address pairs in remapping, i.e., size of sparse matrix num_wgts: Number of weights per vertice for given remapping (we only handle num_wgts == 1 below) = 1 Bilinear Destination grid value determined by weights times known source grid values at vertices of source quadrilateral that bounds destination point P One weight per vertice guarantees fxm but is not conservative Bilinear requires logically rectangular grid = 1 Distance-based: Distance-weighted uses values at num_neighbors points The weight is inversely proportional to the angular distance from the destination point to each neighbor on the source grid = 3 Second-order conservative: Described in Jones, P. W. (1999), Monthly Weather Review, 127, 2204-2210 First-order conservative schemes assume fluxes are constant within gridcell Destination fluxes are simple summations of sources fluxes weighted by overlap areas Old clm and bds remappers use a first-order algorithm Second-order improves this by using a first-order Taylor expansion of flux Source flux is centroid value plus directional offset determined by dot product of directional gradient and vector pointing from vertice to centroid. Three weights per vertice are centroid weight, weight times local theta-gradient from centroid to vertice, and weight times local phi-gradient from centroid to vertice. = 4 Bicubic: The four weights are gradients in each direction plus a cross-gradient term Same principle as bilinear, but more weights per vertice Bicubic requires logically rectangular grid wgt: Maximum number of source cells contributing to destination cell is not a dimension in SCRIP remapping files because SCRIP stores everying in 1-D sparse matrix arrays Definition of sparse matrix formulations and normalization terminology, SCRIP manual p. 8, 13, 16: for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ // Remap source function f = 1 in all unmasked source gridcells, zero elsewhere, to function F on destination grid // Normalization: fractional area (fracarea) (F = 1 where destination overlaps umasked source grid) dst[ddr_dst[lnk_idx]]+=src[ddr_src[lnk_idx]]*remap_matrix[lnk_idx,0]; // Normalization: destination area (destarea) (weights in each destination cell sum to its area frcation) dst[ddr_dst[lnk_idx]]+=src[ddr_src[lnk_idx]]*remap_matrix[lnk_idx,0]/dst_area[ddr_dst[lnk_idx]]; // Normalization: none (F = angular area that participates in remapping) dst[ddr_dst[lnk_idx]]+=src[ddr_src[lnk_idx]]*remap_matrix[lnk_idx,0]/(dst_area[ddr_dst[lnk_idx]]*dst_frc[ddr_dst[lnk_idx]); } // end loop over lnk Documentation: NCL special cases described in popRemap.ncl, e.g., at https://github.com/yyr/ncl/blob/master/ni/src/examples/gsun/popRemap.ncl ESMF Regridding Status: https://www.earthsystemcog.org/projects/esmf Sample regrid T42->POP43, SCRIP: ncks -O --map=${DATA}/scrip/rmp_T42_to_POP43_conserv.nc ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc */ const char fnc_nm[]="nco_rgr_wgt()"; /* [sng] Function name */ char *fl_in; char *fl_pth_lcl=NULL; const double rdn2dgr=180.0/M_PI; const double dgr2rdn=M_PI/180.0; const double eps_rlt=1.0e-14; /* [frc] Round-off error tolerance */ double lat_wgt_ttl=0.0; /* [frc] Actual sum of quadrature weights */ double area_out_ttl=0.0; /* [frc] Exact sum of area */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int in_id; /* I [id] Input netCDF file ID */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int dmn_idx; /* [idx] Dimension index */ int dst_grid_corners_id; /* [id] Destination grid corners dimension ID */ int dst_grid_rank_id; /* [id] Destination grid rank dimension ID */ int dst_grid_size_id; /* [id] Destination grid size dimension ID */ int num_links_id; /* [id] Number of links dimension ID */ int num_wgts_id=NC_MIN_INT; /* [id] Number of weights dimension ID */ int src_grid_corners_id; /* [id] Source grid corners dimension ID */ int src_grid_rank_id; /* [id] Source grid rank dimension ID */ int src_grid_size_id; /* [id] Source grid size dimension ID */ long int lat_idx; long int lon_idx; short int bnd_idx; nco_bool FL_RTR_RMT_LCN; nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool flg_dgn_area_out=False; /* [flg] Diagnose area_out from grid boundaries */ nco_bool flg_bnd_1D_usable=False; /* [flg] Usable 1D cell vertices exist */ nco_bool flg_stg=rgr->flg_stg; /* [flg] Write staggered grid with FV output */ nco_grd_2D_typ_enm nco_grd_2D_typ=nco_grd_2D_nil; /* [enm] Two-dimensional grid-type enum */ nco_grd_lat_typ_enm nco_grd_lat_typ=nco_grd_lat_nil; /* [enm] Latitude grid-type enum */ nco_grd_lon_typ_enm nco_grd_lon_typ=nco_grd_lon_nil; /* [enm] Longitude grid-type enum */ nco_mpf_sct mpf; size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stderr,"%s: INFO %s obtaining mapping weights from %s\n",nco_prg_nm_get(),fnc_nm,rgr->fl_map); /* Duplicate (because nco_fl_mk_lcl() free()'s fl_in) */ fl_in=(char *)strdup(rgr->fl_map); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,&in_id); /* Identify mapping file type using string generated by weight-generator: ESMF: title = "ESMF Offline Regridding Weight Generator" ESMF_weight_only: title = "ESMF Regrid Weight Generator" NCO: Title = "netCDF Operators (NCO) Offline Regridding Weight Generator" MBTR: Title = "MOAB-TempestRemap Online Regridding Weight Generator" SCRIP: conventions = "SCRIP" Tempest: Title = "TempestRemap Offline Regridding Weight Generator" */ char *att_val; char *att_cnv_val=NULL; char *att_gnr_val=NULL; char *att_ttl_val=NULL; char *cnv_sng=NULL; /* netCDF standard is uppercase Conventions, though some models user lowercase */ char att_sng_Cnv[]="Conventions"; /* [sng] Unidata standard string (uppercase) */ char att_sng_cnv[]="conventions"; /* [sng] Unidata non-standard string (lowercase) */ char att_sng_gnr[]="weight_generator"; /* [sng] CMIP6 standard string */ char att_sng_Ttl[]="Title"; /* [sng] MBTR, NCO, and Tempest use "Title" attribute. MBTR and Tempest do not use "Conventions" */ char att_sng_ttl[]="title"; /* [sng] ERWG 7.1 weight_only uses "title" not "Conventions" attribute */ char name0_sng[]="name0"; /* [sng] Attribute where Tempest stores least-rapidly-varying dimension name */ nco_rgr_mpf_typ_enm nco_rgr_mpf_typ=nco_rgr_mpf_nil; /* [enm] Type of remapping file */ nco_rgr_typ_enm nco_rgr_typ=nco_rgr_grd_nil; /* [enm] Type of grid conversion */ /* Look for map-type signature in [cC]onventions or [tT]itle attribute */ att_cnv_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_cnv); if(!att_cnv_val) att_cnv_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_Cnv); att_gnr_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_gnr); att_ttl_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_ttl); if(!att_ttl_val) att_ttl_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_Ttl); /* Either "[cC]onventions" or "[tT]itle" attribute determines map-file type... */ if(att_cnv_val && strstr(att_cnv_val,"SCRIP")) nco_rgr_mpf_typ=nco_rgr_mpf_SCRIP; if(nco_rgr_mpf_typ == nco_rgr_mpf_nil && att_ttl_val){ if(strstr(att_ttl_val,"ESMF Offline Regridding Weight Generator")) nco_rgr_mpf_typ=nco_rgr_mpf_ESMF; else if(strstr(att_ttl_val,"netCDF Operators")) nco_rgr_mpf_typ=nco_rgr_mpf_NCO; else if(strstr(att_ttl_val,"MOAB-TempestRemap")) nco_rgr_mpf_typ=nco_rgr_mpf_MBTR; else if(strstr(att_ttl_val,"Tempest")) nco_rgr_mpf_typ=nco_rgr_mpf_Tempest; else if(strstr(att_ttl_val,"ESMF Regrid Weight Generator")) nco_rgr_mpf_typ=nco_rgr_mpf_ESMF_weight_only; } /* !att_ttl_val */ if(nco_rgr_mpf_typ == nco_rgr_mpf_nil && att_cnv_val){ if(strstr(att_cnv_val,"NCO")) nco_rgr_mpf_typ=nco_rgr_mpf_NCO; } /* !att_gnr_val */ if(nco_rgr_mpf_typ == nco_rgr_mpf_nil && att_gnr_val){ if(strstr(att_gnr_val,"NCO")) nco_rgr_mpf_typ=nco_rgr_mpf_NCO; } /* !att_gnr_val */ if(nco_rgr_mpf_typ == nco_rgr_mpf_nil){ (void)fprintf(stderr,"%s: WARNING %s unable to discern map-file type from global attributes \"[cC]onventions\" = \"%s\" and/or \"[tT]itle\" = \"%s\" and/or \"weight_generator\" = \"%s\"\n",nco_prg_nm_get(),fnc_nm,att_cnv_val ? att_cnv_val : "",att_ttl_val ? att_ttl_val : "",att_gnr_val ? att_gnr_val : ""); nco_rgr_mpf_typ=nco_rgr_mpf_unknown; } /* !nco_rgr_mpf_typ */ if(att_cnv_val) att_cnv_val=(char *)nco_free(att_cnv_val); if(att_gnr_val) att_gnr_val=(char *)nco_free(att_gnr_val); if(att_ttl_val) att_ttl_val=(char *)nco_free(att_ttl_val); switch(nco_rgr_mpf_typ){ case nco_rgr_mpf_SCRIP: rcd+=nco_inq_dimid(in_id,"src_grid_size",&src_grid_size_id); rcd+=nco_inq_dimid(in_id,"dst_grid_size",&dst_grid_size_id); rcd+=nco_inq_dimid(in_id,"src_grid_corners",&src_grid_corners_id); rcd+=nco_inq_dimid(in_id,"dst_grid_corners",&dst_grid_corners_id); rcd+=nco_inq_dimid(in_id,"src_grid_rank",&src_grid_rank_id); rcd+=nco_inq_dimid(in_id,"dst_grid_rank",&dst_grid_rank_id); rcd+=nco_inq_dimid(in_id,"num_links",&num_links_id); rcd+=nco_inq_dimid(in_id,"num_wgts",&num_wgts_id); break; case nco_rgr_mpf_ESMF_weight_only: rcd+=nco_inq_dimid(in_id,"n_s",&num_links_id); break; case nco_rgr_mpf_ESMF: case nco_rgr_mpf_MBTR: case nco_rgr_mpf_NCO: case nco_rgr_mpf_Tempest: case nco_rgr_mpf_unknown: rcd+=nco_inq_dimid(in_id,"n_a",&src_grid_size_id); rcd+=nco_inq_dimid(in_id,"n_b",&dst_grid_size_id); rcd+=nco_inq_dimid(in_id,"nv_a",&src_grid_corners_id); rcd+=nco_inq_dimid(in_id,"nv_b",&dst_grid_corners_id); rcd+=nco_inq_dimid(in_id,"src_grid_rank",&src_grid_rank_id); rcd+=nco_inq_dimid(in_id,"dst_grid_rank",&dst_grid_rank_id); if(nco_rgr_mpf_typ != nco_rgr_mpf_Tempest){ rcd+=nco_inq_dimid_flg(in_id,"num_wgts",&num_wgts_id); if(rcd != NC_NOERR){ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s reports map-file does not contain \"num_wgts\" dimension. ERWG always produces this as an orphan dimension, so post-processing could have removed it without harming other map-file fields. No harm, no foul.\n",nco_prg_nm_get(),fnc_nm); rcd=NC_NOERR; } /* !rcd */ } /* !nco_rgr_mpf_Tempest */ rcd+=nco_inq_dimid(in_id,"n_s",&num_links_id); break; default: (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unknown map-file type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_generic_err(); /* NB: This return never executes because nco_dfl_case_generic_err() calls exit() Return placed here to suppress clang -Wsometimes-uninitialized warnings This is done many other times throughout the code, though explained only once, here */ return NCO_ERR; break; } /* end switch */ /* Use dimension IDs to get dimension sizes */ rcd+=nco_inq_dimlen(in_id,num_links_id,&mpf.num_links); if(nco_rgr_mpf_typ != nco_rgr_mpf_ESMF_weight_only){ rcd+=nco_inq_dimlen(in_id,src_grid_size_id,&mpf.src_grid_size); rcd+=nco_inq_dimlen(in_id,dst_grid_size_id,&mpf.dst_grid_size); rcd+=nco_inq_dimlen(in_id,src_grid_corners_id,&mpf.src_grid_corners); rcd+=nco_inq_dimlen(in_id,dst_grid_corners_id,&mpf.dst_grid_corners); rcd+=nco_inq_dimlen(in_id,src_grid_rank_id,&mpf.src_grid_rank); rcd+=nco_inq_dimlen(in_id,dst_grid_rank_id,&mpf.dst_grid_rank); /* TempestRemap does not generate num_wgts */ if(nco_rgr_mpf_typ == nco_rgr_mpf_MBTR || nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || num_wgts_id == NC_MIN_INT){ mpf.num_wgts=int_CEWI; }else{ rcd+=nco_inq_dimlen(in_id,num_wgts_id,&mpf.num_wgts); } /* !num_wgts_id */ assert(mpf.src_grid_size < INT_MAX && mpf.dst_grid_size < INT_MAX); }else{ mpf.src_grid_size=long_CEWI; mpf.dst_grid_size=long_CEWI; mpf.src_grid_corners=long_CEWI; mpf.dst_grid_corners=long_CEWI; mpf.src_grid_rank=long_CEWI; mpf.dst_grid_rank=long_CEWI; mpf.num_wgts=int_CEWI; } /* !ESMF_weight_only */ cnv_sng=strdup("normalization"); nco_rgr_nrm_typ_enm nco_rgr_nrm_typ=nco_rgr_nrm_nil; att_val=nco_char_att_get(in_id,NC_GLOBAL,cnv_sng); if(att_val){ if(strstr(att_val,"fracarea")) nco_rgr_nrm_typ=nco_rgr_nrm_fracarea; /* 20190912: map_gx1v6T_to_1x1_bilin.nc and map_0.1T_tripole_to_0.1x0.1_bilin.nc store "fracarea" in normalization attribute. I think NCAR created both maps for POP, probably by running ERWG with option --norm_type=fracarea. Hence "fracarea" seems to be the NCAR-way of guaranteeing that ESMF re-normalization is not performed by default. */ if(strstr(att_val,"destarea")) nco_rgr_nrm_typ=nco_rgr_nrm_destarea; /* ESMF conserve "aave" and bilinear "bilin" generate "destarea" by default */ if(strstr(att_val,"none")) nco_rgr_nrm_typ=nco_rgr_nrm_none; if(att_val) att_val=(char *)nco_free(att_val); }else{ /* 20150712: Tempest does not store a normalization attribute 20170620: ESMF weight_only does not store a normalization attribute 20190312: NCO does not yet store a normalization attribute */ if(nco_rgr_mpf_typ == nco_rgr_mpf_MBTR || nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || nco_rgr_mpf_typ == nco_rgr_mpf_NCO || nco_rgr_mpf_typ == nco_rgr_mpf_unknown || nco_rgr_mpf_typ == nco_rgr_mpf_ESMF_weight_only) nco_rgr_nrm_typ=nco_rgr_nrm_unknown; } /* endif normalization */ assert(nco_rgr_nrm_typ != nco_rgr_nrm_nil); if(cnv_sng) cnv_sng=(char *)nco_free(cnv_sng); cnv_sng=strdup("map_method"); nco_rgr_mth_typ_enm nco_rgr_mth_typ=nco_rgr_mth_nil; att_val=nco_char_att_get(in_id,NC_GLOBAL,cnv_sng); if(att_val){ if(strcasestr(att_val,"Conservative")) nco_rgr_mth_typ=nco_rgr_mth_conservative; if(strcasestr(att_val,"Bilinear")) nco_rgr_mth_typ=nco_rgr_mth_bilinear; if(strcasestr(att_val,"none")) nco_rgr_mth_typ=nco_rgr_mth_none; if(att_val) att_val=(char *)nco_free(att_val); }else{ /* Tempest does not store a map_method attribute */ if(nco_rgr_mpf_typ == nco_rgr_mpf_MBTR || nco_rgr_mpf_typ == nco_rgr_mpf_NCO || nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || nco_rgr_mpf_typ == nco_rgr_mpf_unknown) nco_rgr_mth_typ=nco_rgr_mth_unknown; } /* endif */ if(nco_rgr_mth_typ == nco_rgr_mth_nil) (void)fprintf(stdout,"%s: WARNING %s reports map global attribute %s = %s does not match SCRIP/ESMF conventions that support only values of \"Conservative\" and \"Bilinear\" for this attribute. Proceeding anyway...\n",nco_prg_nm_get(),fnc_nm,cnv_sng,att_val); if(cnv_sng) cnv_sng=(char *)nco_free(cnv_sng); if(nco_dbg_lvl_get() >= nco_dbg_scl){ (void)fprintf(stderr,"%s: INFO %s regridding input metadata and grid sizes: ",nco_prg_nm_get(),fnc_nm); (void)fprintf(stderr,"mapfile_generator = %s, map_method = %s, normalization = %s, src_grid_size = n_a = %li, dst_grid_size = n_b = %li, src_grid_corners = nv_a = %li, dst_grid_corners = nv_b = %li, src_grid_rank = %li, dst_grid_rank = %li, num_links = n_s = %li, num_wgts = %li\n",nco_rgr_mpf_sng(nco_rgr_mpf_typ),nco_rgr_mth_sng(nco_rgr_mth_typ),nco_rgr_nrm_sng(nco_rgr_nrm_typ),mpf.src_grid_size,mpf.dst_grid_size,mpf.src_grid_corners,mpf.dst_grid_corners,mpf.src_grid_rank,mpf.dst_grid_rank,mpf.num_links,mpf.num_wgts); } /* endif dbg */ /* 20190726: Allow normalization type to be "none" for bilinear regridding which UKMO SCRIP files set to "none"*/ if(nco_rgr_mth_typ == nco_rgr_mth_conservative && nco_rgr_nrm_typ == nco_rgr_nrm_none){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports requested normalization type = %s is not yet supported. Specifically, masks specified by a mask variable (dst_grid_imask,mask_b) are ignored. More specifically, any destination mask information is assumed to be built into the weight array so that no source points will contribute to masked locations. Talk to Charlie if you want this changed.\n",nco_prg_nm_get(),fnc_nm,nco_rgr_nrm_sng(nco_rgr_nrm_typ)); nco_exit(EXIT_FAILURE); } /* !msk */ /* Got to here in bullet-proofing code for weight-only map-files */ if(nco_rgr_mpf_typ == nco_rgr_mpf_ESMF_weight_only) (void)fprintf(stderr,"%s: WARNING %s reached end of ESMF_weight_only section\n",nco_prg_nm_get(),fnc_nm); assert(nco_rgr_mpf_typ != nco_rgr_mpf_ESMF_weight_only); /* Set type of grid conversion */ if(mpf.src_grid_rank == 1 && mpf.dst_grid_rank == 1) nco_rgr_typ=nco_rgr_grd_1D_to_1D; if(mpf.src_grid_rank == 1 && mpf.dst_grid_rank == 2) nco_rgr_typ=nco_rgr_grd_1D_to_2D; if(mpf.src_grid_rank == 2 && mpf.dst_grid_rank == 1) nco_rgr_typ=nco_rgr_grd_2D_to_1D; if(mpf.src_grid_rank == 2 && mpf.dst_grid_rank == 2) nco_rgr_typ=nco_rgr_grd_2D_to_2D; assert(nco_rgr_typ != nco_rgr_grd_nil); /* Save typing later */ nco_bool flg_grd_in_1D_dat_in_2D=False; nco_bool flg_grd_in_1D=False; nco_bool flg_grd_in_2D=False; nco_bool flg_grd_out_1D=False; nco_bool flg_grd_out_2D=False; if(nco_rgr_typ == nco_rgr_grd_1D_to_1D || nco_rgr_typ == nco_rgr_grd_1D_to_2D) flg_grd_in_1D=True; if(nco_rgr_typ == nco_rgr_grd_2D_to_1D || nco_rgr_typ == nco_rgr_grd_2D_to_2D) flg_grd_in_2D=True; if(nco_rgr_typ == nco_rgr_grd_1D_to_1D || nco_rgr_typ == nco_rgr_grd_2D_to_1D) flg_grd_out_1D=True; if(nco_rgr_typ == nco_rgr_grd_1D_to_2D || nco_rgr_typ == nco_rgr_grd_2D_to_2D) flg_grd_out_2D=True; int dmn_nbr_hrz_crd; /* [nbr] Number of horizontal dimensions in output grid */ if(flg_grd_out_2D) dmn_nbr_hrz_crd=2; else dmn_nbr_hrz_crd=1; /* Obtain grid values necessary to compute output latitude and longitude coordinates */ int area_dst_id; /* [id] Area variable ID */ int col_src_adr_id; /* [id] Source address (col) variable ID */ int dmn_sz_in_int_id; /* [id] Source grid dimension sizes ID */ int dmn_sz_out_int_id; /* [id] Destination grid dimension sizes ID */ int dst_grd_crn_lat_id; /* [id] Destination grid corner latitudes variable ID */ int dst_grd_crn_lon_id; /* [id] Destination grid corner longitudes variable ID */ int dst_grd_ctr_lat_id; /* [id] Destination grid center latitudes variable ID */ int dst_grd_ctr_lon_id; /* [id] Destination grid center longitudes variable ID */ int frc_dst_id; /* [id] Fraction variable ID */ int msk_dst_id=NC_MIN_INT; /* [id] Mask variable ID */ int row_dst_adr_id; /* [id] Destination address (row) variable ID */ int wgt_raw_id; /* [id] Remap matrix variable ID */ switch(nco_rgr_mpf_typ){ /* Obtain fields whose name depends on mapfile type */ case nco_rgr_mpf_SCRIP: rcd+=nco_inq_varid(in_id,"dst_grid_area",&area_dst_id); /* ESMF: area_b */ rcd+=nco_inq_varid(in_id,"dst_grid_center_lon",&dst_grd_ctr_lon_id); /* ESMF: xc_b */ rcd+=nco_inq_varid(in_id,"dst_grid_center_lat",&dst_grd_ctr_lat_id); /* ESMF: yc_b */ rcd+=nco_inq_varid(in_id,"dst_grid_corner_lon",&dst_grd_crn_lon_id); /* ESMF: xv_b */ rcd+=nco_inq_varid(in_id,"dst_grid_corner_lat",&dst_grd_crn_lat_id); /* ESMF: yv_b */ rcd+=nco_inq_varid(in_id,"dst_grid_frac",&frc_dst_id); /* ESMF: frac_b */ rcd+=nco_inq_varid(in_id,"dst_address",&row_dst_adr_id); /* ESMF: row */ rcd+=nco_inq_varid(in_id,"src_address",&col_src_adr_id); /* ESMF: col */ rcd+=nco_inq_varid(in_id,"remap_matrix",&wgt_raw_id); /* NB: remap_matrix[num_links,num_wgts] != S[n_s] */ break; case nco_rgr_mpf_ESMF: case nco_rgr_mpf_ESMF_weight_only: case nco_rgr_mpf_MBTR: case nco_rgr_mpf_NCO: case nco_rgr_mpf_Tempest: case nco_rgr_mpf_unknown: if(nco_rgr_mpf_typ != nco_rgr_mpf_ESMF_weight_only){ rcd+=nco_inq_varid(in_id,"area_b",&area_dst_id); /* SCRIP: dst_grid_area */ rcd+=nco_inq_varid(in_id,"xc_b",&dst_grd_ctr_lon_id); /* SCRIP: dst_grid_center_lon */ rcd+=nco_inq_varid(in_id,"yc_b",&dst_grd_ctr_lat_id); /* SCRIP: dst_grid_center_lat */ rcd+=nco_inq_varid(in_id,"xv_b",&dst_grd_crn_lon_id); /* SCRIP: dst_grid_corner_lon */ rcd+=nco_inq_varid(in_id,"yv_b",&dst_grd_crn_lat_id); /* SCRIP: dst_grid_corner_lat */ rcd+=nco_inq_varid(in_id,"frac_b",&frc_dst_id); /* SCRIP: dst_grid_frac */ } /* !nco_rgr_mpf_ESMF_weight_only */ rcd+=nco_inq_varid(in_id,"row",&row_dst_adr_id); /* SCRIP: dst_address */ rcd+=nco_inq_varid(in_id,"col",&col_src_adr_id); /* SCRIP: src_address */ rcd+=nco_inq_varid(in_id,"S",&wgt_raw_id); /* NB: remap_matrix[num_links,num_wgts] != S[n_s] */ break; default: (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unknown map file type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_generic_err(); /* NB: This return never executes because nco_dfl_case_generic_err() calls exit() Return placed here to suppress clang -Wsometimes-uninitialized warnings This is done many other times throughout the code, though explained only once, here */ return NCO_ERR; break; } /* end switch */ /* Obtain fields whose presence depends on mapfile type */ nco_bool flg_msk_out=rgr->flg_msk_out; /* [flg] Add mask to output */ nco_bool flg_msk_apl=rgr->flg_msk_apl; /* [flg] Apply msk_out to variables after regridding */ msk_dst_id=NC_MIN_INT; if(flg_msk_out || flg_msk_apl){ switch(nco_rgr_mpf_typ){ case nco_rgr_mpf_SCRIP: rcd=nco_inq_varid_flg(in_id,"dst_grid_imask",&msk_dst_id); /* ESMF: mask_b */ break; case nco_rgr_mpf_ESMF: case nco_rgr_mpf_MBTR: case nco_rgr_mpf_NCO: case nco_rgr_mpf_Tempest: case nco_rgr_mpf_unknown: /* 20190315: TempestRemap did not propagate mask_a/b until ~201902 20210519: MBTR did not propagate mask_a/b as of ~202105 */ rcd=nco_inq_varid_flg(in_id,"mask_b",&msk_dst_id); /* SCRIP: dst_grid_imask */ break; default: (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unknown map-file type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_generic_err(); } /* !nco_rgr_mpf_typ */ if(rcd == NC_ENOTVAR){ if(flg_msk_apl){ (void)fprintf(stderr,"%s: ERROR %s reports that user requested (with --mask_apply) the regridder to apply the destination mask field to variables after regridding. Unfortunately, the map-file lacks a destination mask of the expected name (usually \"mask_b\").\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* flg_msk_apl */ (void)fprintf(stderr,"%s: INFO %s reports map-file lacks mask_b. %sContinuing anyway without masks...\n",nco_prg_nm_get(),fnc_nm,(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest || nco_rgr_mpf_typ == nco_rgr_mpf_MBTR) ? "Probably this is either a TempestRemap map-file created before ~201902 when TR began to propagate mask_a/b variables, or it is a MOAB-TempestRemap file which has never (as of 202105) propagated mask_a/b variables" : ""); rcd=NC_NOERR; } /* !rcd */ if(msk_dst_id == NC_MIN_INT) flg_msk_out=False; } /* !flg_msk_out */ /* Obtain fields whose names are independent of mapfile type */ rcd+=nco_inq_varid(in_id,"src_grid_dims",&dmn_sz_in_int_id); rcd+=nco_inq_varid(in_id,"dst_grid_dims",&dmn_sz_out_int_id); int lon_psn_src; /* [idx] Ordinal position of longitude in rectangular source grid dimension-size array */ int lat_psn_src; /* [idx] Ordinal position of latitude in rectangular source grid dimension-size array */ int lon_psn_dst=int_CEWI; /* [idx] Ordinal position of longitude in rectangular destination grid dimension-size array */ int lat_psn_dst=int_CEWI; /* [idx] Ordinal position of latitude in rectangular destination grid dimension-size array */ if(flg_grd_in_2D){ lon_psn_src=0; /* SCRIP introduced [lon,lat] convention because more natural for Fortran */ lat_psn_src=1; if(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest){ /* Until 20150814, Tempest stored [src/dst]_grid_dims as [lat,lon] unlike SCRIP's [lon,lat] order Newer behavior follows SCRIP [lon,lat] order Challenge: Support both older and newer Tempest mapfiles Tempest (unlike SCRIP and ESMF) annotates mapfile [src/dst]_grid_dims with attributes that identify axis to which each element of [src/dst]_grid_dims refers Solution: Use Tempest mapfile [src/dst]_grid_dims attributes "name0" and/or "name1" to determine if axes' positions follow old order */ att_val=nco_char_att_get(in_id,dmn_sz_in_int_id,name0_sng); if(att_val){ if(strstr(att_val,"lat")){ lon_psn_src=1; lat_psn_src=0; } /* !lat */ if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ } /* !Tempest */ } /* !flg_grd_in_2D */ if(flg_grd_out_2D){ lon_psn_dst=0; lat_psn_dst=1; if(nco_rgr_mpf_typ == nco_rgr_mpf_Tempest){ att_val=nco_char_att_get(in_id,dmn_sz_in_int_id,name0_sng); if(att_val){ if(strstr(att_val,"lat")){ lon_psn_dst=1; lat_psn_dst=0; } /* !lat */ if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ } /* !Tempest */ } /* !flg_grd_out_2D */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ const int dmn_nbr_3D=3; /* [nbr] Rank of 3-D grid variables */ const int dmn_nbr_grd_max=dmn_nbr_3D; /* [nbr] Maximum rank of grid variables */ double *area_out; /* [sr] Area of destination grid */ double *frc_out=NULL; /* [frc] Fraction of destination grid */ double *lat_bnd_out=NULL_CEWI; /* [dgr] Latitude boundaries of rectangular destination grid */ double *lat_crn_out=NULL; /* [dgr] Latitude corners of rectangular destination grid */ double *lat_ctr_out=NULL_CEWI; /* [dgr] Latitude centers of rectangular destination grid */ double *lat_ntf_out=NULL; /* [dgr] Latitude interfaces of rectangular destination grid */ double *lat_wgt_out=NULL; /* [dgr] Latitude weights of rectangular destination grid */ double *lon_bnd_out=NULL_CEWI; /* [dgr] Longitude boundaries of rectangular destination grid */ double *lon_crn_out=NULL; /* [dgr] Longitude corners of rectangular destination grid */ double *lon_ctr_out=NULL_CEWI; /* [dgr] Longitude centers of rectangular destination grid */ double *lon_ntf_out=NULL; /* [dgr] Longitude interfaces of rectangular destination grid */ double *slat_ctr_out=NULL_CEWI; /* [dgr] Latitude centers of staggered FV destination grid */ double *slat_wgt_out=NULL_CEWI; /* [frc] Latitude weights of staggered FV destination grid */ double *slon_ctr_out=NULL_CEWI; /* [dgr] Longitude centers of staggered FV destination grid */ double *wgt_raw; /* [frc] Remapping weights */ int *col_src_adr; /* [idx] Source address (col) */ int *row_dst_adr; /* [idx] Destination address (row) */ int *msk_out=NULL; /* [flg] Mask on destination grid */ int *dmn_sz_in_int; /* [nbr] Array of dimension sizes of source grid */ int *dmn_sz_out_int; /* [nbr] Array of dimension sizes of destination grid */ long *dmn_cnt_in=NULL; long *dmn_cnt_out=NULL; long *dmn_cnt=NULL; long *dmn_srt=NULL; long *dmn_srd=NULL; long idx; /* [idx] Counting index for unrolled grids */ /* Allocate space to hold dimension metadata for destination grid */ dmn_srt=(long *)nco_malloc(dmn_nbr_grd_max*sizeof(long)); dmn_cnt=(long *)nco_malloc(dmn_nbr_grd_max*sizeof(long)); dmn_srd=(long *)nco_malloc(dmn_nbr_grd_max*sizeof(long)); dmn_srt[0]=0L; dmn_cnt[0]=mpf.src_grid_rank; dmn_sz_in_int=(int *)nco_malloc(mpf.src_grid_rank*nco_typ_lng((nc_type)NC_INT)); rcd=nco_get_vara(in_id,dmn_sz_in_int_id,dmn_srt,dmn_cnt,dmn_sz_in_int,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=mpf.dst_grid_rank; dmn_sz_out_int=(int *)nco_malloc(mpf.dst_grid_rank*nco_typ_lng((nc_type)NC_INT)); rcd=nco_get_vara(in_id,dmn_sz_out_int_id,dmn_srt,dmn_cnt,dmn_sz_out_int,(nc_type)NC_INT); /* Check-for and workaround faulty Tempest and MPAS-O/I grid sizes */ if(flg_grd_in_1D && (mpf.src_grid_size != dmn_sz_in_int[0])){ (void)fprintf(stdout,"%s: INFO %s reports input grid dimension sizes disagree: mpf.src_grid_size = %ld != %d = dmn_sz_in[0]. Problem may be caused by incorrect src_grid_dims variable. This is a known issue with some TempestRemap mapfiles generated prior to ~20150901, and in some ESMF mapfiles for MPAS-O/I. This problem can be safely ignored if workaround succeeds. Attempting workaround ...\n",nco_prg_nm_get(),fnc_nm,mpf.src_grid_size,dmn_sz_in_int[0]); dmn_sz_in_int[0]=mpf.src_grid_size; } /* !bug */ if(flg_grd_out_1D && (mpf.dst_grid_size != dmn_sz_out_int[0])){ (void)fprintf(stdout,"%s: INFO %s reports output grid dimension sizes disagree: mpf.dst_grid_size = %ld != %d = dmn_sz_out[0]. Problem may be caused by incorrect dst_grid_dims variable. This is a known issue with some TempestRemap mapfiles generated prior to ~20150901, and in some ESMF mapfiles for MPAS-O/I. This problem can be safely ignored if workaround succeeds. Attempting workaround ...\n",nco_prg_nm_get(),fnc_nm,mpf.dst_grid_size,dmn_sz_out_int[0]); dmn_sz_out_int[0]=mpf.dst_grid_size; } /* !bug */ long col_nbr_in; /* [idx] Number of columns in source grid */ long lon_nbr_in; /* [idx] Number of longitudes in rectangular source grid */ long lat_nbr_in; /* [idx] Number of latitudes in rectangular source grid */ const size_t grd_sz_in=mpf.src_grid_size; /* [nbr] Number of elements in single layer of input grid */ const size_t grd_sz_out=mpf.dst_grid_size; /* [nbr] Number of elements in single layer of output grid */ if(flg_grd_in_1D){ col_nbr_in=dmn_sz_in_int[0]; lon_nbr_in=dmn_sz_in_int[0]; lat_nbr_in=dmn_sz_in_int[0]; }else if(flg_grd_in_2D){ col_nbr_in=0; lon_nbr_in=dmn_sz_in_int[lon_psn_src]; lat_nbr_in=dmn_sz_in_int[lat_psn_src]; /* Sanity-check */ assert(lat_nbr_in*lon_nbr_in == (long)grd_sz_in); } /* !src_grid_rank */ const int bnd_tm_nbr_out=2; /* [nbr] Number of boundaries for output time */ int bnd_nbr_out=int_CEWI; /* [nbr] Number of boundaries for output time and rectangular grid coordinates, and number of vertices for output non-rectangular grid coordinates */ long col_nbr_out=long_CEWI; /* [nbr] Number of columns in destination grid */ long lon_nbr_out=long_CEWI; /* [nbr] Number of longitudes in rectangular destination grid */ long lat_nbr_out=long_CEWI; /* [nbr] Number of latitudes in rectangular destination grid */ long slat_nbr_out=long_CEWI; /* [nbr] Number of latitudes in staggered FV grid destination grid */ long slon_nbr_out=long_CEWI; /* [nbr] Number of longitudes in staggered FV grid destination grid */ if(flg_grd_out_1D){ bnd_nbr_out=mpf.dst_grid_corners; col_nbr_out=dmn_sz_out_int[0]; lat_nbr_out=dmn_sz_out_int[0]; lon_nbr_out=dmn_sz_out_int[0]; /* Sanity-check */ assert(col_nbr_out == (long)grd_sz_out); }else if(flg_grd_out_2D){ col_nbr_out=lat_nbr_out*lon_nbr_out; lat_nbr_out=dmn_sz_out_int[lat_psn_dst]; lon_nbr_out=dmn_sz_out_int[lon_psn_dst]; slat_nbr_out=lat_nbr_out-1L; slon_nbr_out=lon_nbr_out; /* Sanity-check */ assert(lat_nbr_out*lon_nbr_out == (long)grd_sz_out); } /* !dst_grid_rank */ /* Ensure coordinates are in degrees not radians for simplicity and CF-compliance NB: ${DATA}/scrip/rmp_T42_to_POP43_conserv.nc has [xy]?_a in degrees and [xy]?_b in radians! */ nco_bool flg_crd_rdn=False; /* [flg] Destination coordinates are in radians not degrees */ char unt_sng[]="units"; /* [sng] netCDF-standard units attribute name */ att_val=nco_char_att_get(in_id,dst_grd_ctr_lat_id,unt_sng); if(att_val){ /* Match "radian" and "radians" */ if(strstr(att_val,"radian")) flg_crd_rdn=True; if(att_val) att_val=(char *)nco_free(att_val); } /* end rcd && att_typ */ nco_bool flg_grd_out_crv=False; /* [flg] Curvilinear coordinates */ nco_bool flg_grd_out_rct=False; /* [flg] Rectangular coordinates */ const nc_type crd_typ_out=NC_DOUBLE; if(flg_grd_out_2D){ lon_ctr_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); lat_ctr_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); lon_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*grd_sz_out*nco_typ_lng(crd_typ_out)); lat_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*grd_sz_out*nco_typ_lng(crd_typ_out)); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lon_id,dmn_srt,dmn_cnt,lon_ctr_out,crd_typ_out); rcd=nco_get_vara(in_id,dst_grd_ctr_lat_id,dmn_srt,dmn_cnt,lat_ctr_out,crd_typ_out); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_out; dmn_cnt[1]=mpf.dst_grid_corners; rcd=nco_get_vara(in_id,dst_grd_crn_lon_id,dmn_srt,dmn_cnt,lon_crn_out,crd_typ_out); rcd=nco_get_vara(in_id,dst_grd_crn_lat_id,dmn_srt,dmn_cnt,lat_crn_out,crd_typ_out); /* User may specify curvilinear grid (with --rgr crv). Otherwise, manually test for curvilinear source grid. */ flg_grd_out_crv=rgr->flg_crv; /* [flg] Curvilinear coordinates */ if(flg_grd_out_crv){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Output grid specified to be %s\n",nco_prg_nm_get(),flg_grd_out_crv ? "Curvilinear" : "Rectangular"); }else{ long idx_tst=long_CEWI; /* [idx] Index of first latitude or longitude */ for(idx=0;idx<(long)grd_sz_out;idx++){ if(idx%lon_nbr_out == 0) idx_tst=idx; if(lat_ctr_out[idx] != lat_ctr_out[idx_tst]) break; // (void)fprintf(stdout,"%s: DEBUG lat_ctr_out[%li] = %g, lat_ctr_out[%li] = %g\n",nco_prg_nm_get(),idx,lat_ctr_out[idx],idx_tst,lat_ctr_out[idx_tst]); /* fxm: also test lon */ } /* !rectangular */ if(idx != (long)grd_sz_out) flg_grd_out_crv=True; else flg_grd_out_rct=True; if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO Output grid detected to be %s\n",nco_prg_nm_get(),flg_grd_out_crv ? "Curvilinear" : "Rectangular"); } /* !flg_grd_out_crv */ if(flg_grd_out_crv) bnd_nbr_out=mpf.dst_grid_corners; if(flg_grd_out_rct) bnd_nbr_out=2; /* NB: Assumes rectangular latitude and longitude and is invalid for other quadrilaterals */ } /* !flg_grd_out_2D */ if(nco_dbg_lvl_get() >= nco_dbg_scl){ (void)fprintf(stderr,"%s: INFO %s grid conversion type = %s with expected input and prescribed output grid sizes: ",nco_prg_nm_get(),fnc_nm,nco_rgr_grd_sng(nco_rgr_typ)); (void)fprintf(stderr,"lat_in = %li, lon_in = %li, col_in = %li, lat_out = %li, lon_out = %li, col_out = %li\n",lat_nbr_in,lon_nbr_in,col_nbr_in,lat_nbr_out,lon_nbr_out,col_nbr_out); } /* endif dbg */ /* Allocate space for and obtain coordinates */ if(flg_grd_out_1D){ lon_ctr_out=(double *)nco_malloc(col_nbr_out*nco_typ_lng(crd_typ_out)); lat_ctr_out=(double *)nco_malloc(col_nbr_out*nco_typ_lng(crd_typ_out)); lon_bnd_out=(double *)nco_malloc(col_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); lat_bnd_out=(double *)nco_malloc(col_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); } /* !flg_grd_out_1D */ if(flg_grd_out_rct){ if(lat_ctr_out) lat_ctr_out=(double *)nco_free(lat_ctr_out); if(lon_ctr_out) lon_ctr_out=(double *)nco_free(lon_ctr_out); if(lat_crn_out) lat_crn_out=(double *)nco_free(lat_crn_out); if(lon_crn_out) lon_crn_out=(double *)nco_free(lon_crn_out); lon_ctr_out=(double *)nco_malloc(lon_nbr_out*nco_typ_lng(crd_typ_out)); lat_ctr_out=(double *)nco_malloc(lat_nbr_out*nco_typ_lng(crd_typ_out)); lon_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*lon_nbr_out*nco_typ_lng(crd_typ_out)); lat_crn_out=(double *)nco_malloc(mpf.dst_grid_corners*lat_nbr_out*nco_typ_lng(crd_typ_out)); lat_wgt_out=(double *)nco_malloc(lat_nbr_out*nco_typ_lng(crd_typ_out)); lon_ntf_out=(double *)nco_malloc((lon_nbr_out+1L)*nco_typ_lng(crd_typ_out)); lat_ntf_out=(double *)nco_malloc((lat_nbr_out+1L)*nco_typ_lng(crd_typ_out)); lon_bnd_out=(double *)nco_malloc(lon_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); lat_bnd_out=(double *)nco_malloc(lat_nbr_out*bnd_nbr_out*nco_typ_lng(crd_typ_out)); } /* !flg_grd_out_rct */ /* Arrays unroll into all longitudes for first latitude, then second latitude, ... Obtain longitudes by reading first block contiguously (unstrided) Obtain latitudes by reading unrolled data with stride of lon_nbr */ if(flg_grd_out_1D){ dmn_srt[0]=0L; dmn_cnt[0]=col_nbr_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lon_id,dmn_srt,dmn_cnt,lon_ctr_out,crd_typ_out); dmn_srt[0]=0L; dmn_cnt[0]=col_nbr_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lat_id,dmn_srt,dmn_cnt,lat_ctr_out,crd_typ_out); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr_out; dmn_cnt[1]=bnd_nbr_out; rcd=nco_get_vara(in_id,dst_grd_crn_lon_id,dmn_srt,dmn_cnt,lon_bnd_out,crd_typ_out); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr_out; dmn_cnt[1]=bnd_nbr_out; rcd=nco_get_vara(in_id,dst_grd_crn_lat_id,dmn_srt,dmn_cnt,lat_bnd_out,crd_typ_out); if(flg_crd_rdn){ for(idx=0;idx<col_nbr_out;idx++){ lon_ctr_out[idx]*=rdn2dgr; lat_ctr_out[idx]*=rdn2dgr; } /* !idx */ for(idx=0;idx<col_nbr_out*bnd_nbr_out;idx++){ lon_bnd_out[idx]*=rdn2dgr; lat_bnd_out[idx]*=rdn2dgr; } /* !idx */ } /* !rdn */ /* Is 1D interface information usable? Yes, unless if all interfaces are zeros NB: fxm Better algorithm for "usable" is that not all interfaces in any cell are equal */ flg_bnd_1D_usable=True; for(idx=0;idx<col_nbr_out*bnd_nbr_out;idx++) if(lon_bnd_out[idx] != 0.0) break; if(idx == col_nbr_out*bnd_nbr_out){ flg_bnd_1D_usable=False; }else{ for(idx=0;idx<col_nbr_out*bnd_nbr_out;idx++) if(lat_bnd_out[idx] != 0.0) break; if(idx == col_nbr_out*bnd_nbr_out) flg_bnd_1D_usable=False; } /* !usable */ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0;idx<lat_nbr_out;idx++){ (void)fprintf(stdout,"lat[%li] = %g, vertices = ",idx,lat_ctr_out[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr_out;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lat_bnd_out[bnd_nbr_out*idx+bnd_idx],bnd_idx == bnd_nbr_out-1 ? "]\n" : ", "); } /* end loop over lat */ for(idx=0;idx<lon_nbr_out;idx++){ (void)fprintf(stdout,"lon[%li] = %g, vertices = ",idx,lon_ctr_out[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr_out;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lon_bnd_out[bnd_nbr_out*idx+bnd_idx],bnd_idx == bnd_nbr_out-1 ? "]\n" : ", "); } /* end loop over lon */ } /* endif dbg */ } /* !flg_grd_out_1D */ if(flg_grd_out_rct){ /* fxm: sub-sample these from the already-read ctr/crn arrays */ dmn_srt[0L]=0L; dmn_cnt[0L]=lon_nbr_out; rcd=nco_get_vara(in_id,dst_grd_ctr_lon_id,dmn_srt,dmn_cnt,lon_ctr_out,crd_typ_out); dmn_srt[0L]=0L; dmn_cnt[0L]=lat_nbr_out; dmn_srd[0L]=lon_nbr_out; rcd=nco_get_vars(in_id,dst_grd_ctr_lat_id,dmn_srt,dmn_cnt,dmn_srd,lat_ctr_out,crd_typ_out); dmn_srt[0L]=dmn_srt[1]=0L; dmn_cnt[0L]=lon_nbr_out; dmn_cnt[1]=mpf.dst_grid_corners; rcd=nco_get_vara(in_id,dst_grd_crn_lon_id,dmn_srt,dmn_cnt,lon_crn_out,crd_typ_out); dmn_srt[0L]=0L; dmn_cnt[0L]=lat_nbr_out; dmn_srd[0L]=lon_nbr_out; dmn_srt[1]=0L; dmn_cnt[1]=mpf.dst_grid_corners; dmn_srd[1]=1L; rcd=nco_get_vars(in_id,dst_grd_crn_lat_id,dmn_srt,dmn_cnt,dmn_srd,lat_crn_out,crd_typ_out); if(flg_crd_rdn){ for(idx=0L;idx<lon_nbr_out;idx++) lon_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<lat_nbr_out;idx++) lat_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<lon_nbr_out*mpf.dst_grid_corners;idx++) lon_crn_out[idx]*=rdn2dgr; for(idx=0L;idx<lat_nbr_out*mpf.dst_grid_corners;idx++) lat_crn_out[idx]*=rdn2dgr; } /* !rdn */ } /* !flg_grd_out_rct */ if(flg_grd_out_crv){ if(flg_crd_rdn){ for(idx=0L;idx<(long)grd_sz_out;idx++) lon_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<(long)grd_sz_out;idx++) lat_ctr_out[idx]*=rdn2dgr; for(idx=0L;idx<(long)grd_sz_out*mpf.dst_grid_corners;idx++) lon_crn_out[idx]*=rdn2dgr; for(idx=0L;idx<(long)grd_sz_out*mpf.dst_grid_corners;idx++) lat_crn_out[idx]*=rdn2dgr; } /* !rdn */ } /* !flg_grd_out_crv */ /* Allocate space for and obtain area, fraction, and mask, which are needed for both 1D and 2D grids */ area_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); dmn_srt[0L]=0L; dmn_cnt[0L]=grd_sz_out; rcd=nco_get_vara(in_id,area_dst_id,dmn_srt,dmn_cnt,area_out,crd_typ_out); frc_out=(double *)nco_malloc(grd_sz_out*nco_typ_lng(crd_typ_out)); dmn_srt[0L]=0L; dmn_cnt[0L]=grd_sz_out; rcd=nco_get_vara(in_id,frc_dst_id,dmn_srt,dmn_cnt,frc_out,crd_typ_out); if(msk_dst_id != NC_MIN_INT){ msk_out=(int *)nco_malloc(grd_sz_out*nco_typ_lng(NC_INT)); dmn_srt[0L]=0L; dmn_cnt[0L]=grd_sz_out; rcd=nco_get_vara(in_id,msk_dst_id,dmn_srt,dmn_cnt,msk_out,(nc_type)NC_INT); } /* !msk */ /* Derive 2D interface boundaries from lat and lon grid-center values NB: Procedures to derive interfaces from midpoints on rectangular grids are theoretically possible However, ESMF often outputs interfaces values (e.g., yv_b) for midpoint coordinates (e.g., yc_b) For example, ACME standard map from ne120np4 to 181x360 has yc_b[0] = yv_b[0] = -90.0 Latitude = -90 is, by definition, not a midpoint coordinate This appears to be an artifact of the non-physical representation of the FV grid, i.e., a grid center located at the pole where longitudes collapse in the model, but cannot be represented as collapsed on a rectangular 2D grid with non-zero areas. Unfortunately, ESMF supports this nonsense by labeling the grid center as at the pole so that applications can easily diagnose an FV grid when they read-in datasets. A superior application could diagnose FV just fine from actual non-polar gridcell centers Maybe ESMF could introduce a flag or something to indicate/avoid this special case? Safer to read boundary interfaces directly from grid corner/vertice arrays in map file Derivation of boundaries xv_b, yv_b from _correct_ xc_b, yc_b is follows Do not implement this procedure until resolving midpoint/center issue described above: lon_ntf_out[0L]=0.5*(lon_ctr_out[0L]+lon_ctr_out[lon_nbr_out-1L])-180.0; // Extrapolation lat_ntf_out[0L]=lat_ctr_out[0L]-0.5*(lat_ctr_out[1L]-lat_ctr_out[0L]); // Extrapolation for(idx=1L;idx<lon_nbr_out;idx++) lon_ntf_out[idx]=0.5*(lon_ctr_out[idx-1L]+lon_ctr_out[idx]); for(idx=1L;idx<lat_nbr_out;idx++) lat_ntf_out[idx]=0.5*(lat_ctr_out[idx-1L]+lat_ctr_out[idx]); lon_ntf_out[lon_nbr_out]=lon_ntf_out[0L]+360.0; lat_ntf_out[lat_nbr_out]=lat_ctr_out[lat_nbr_out-1L]+0.5*(lat_ctr_out[lat_nbr_out-1L]-lat_ctr_out[lat_nbr_out-2L]); */ if(flg_grd_out_rct){ double lon_spn; /* [dgr] Longitude span */ double lat_spn; /* [dgr] Latitude span */ nco_bool flg_s2n=True; /* I [enm] Latitude grid-direction is South-to-North */ if(lat_ctr_out[1L] < lat_ctr_out[0L]) flg_s2n=False; /* Obtain 1-D rectangular interfaces from unrolled 1-D vertice arrays */ for(idx=0L;idx<lon_nbr_out;idx++) lon_ntf_out[idx]=lon_crn_out[mpf.dst_grid_corners*idx]; /* 20201009 The four possible CCW RLL orderings start with the ul, ll, lr, or ur vertice NCO grid generators store vertices in order (0,1,2,3)=(ul,ll,lr,ur) NCO final latitude is in upper vertices (0,3) for S2N grids, lower vertices (1,2) for N2S grids NCO final longitude is in RHS vertices (2,3) for S2N and N2S grids Need generic algorithm to pick easternmost longitude for any of the four CCW orderings What is ESMF vertice ordering? or does ESMF always copy from input grid? Most grid generators probably start with ul or ll so vertice 2 is good choice for easternmost */ // lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-(mpf.dst_grid_corners-1L)]; // ESMF? lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-2L]; // NCO lr if(lon_ntf_out[lon_nbr_out-1] == lon_ntf_out[lon_nbr_out]) lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-1L]; // NCO ur if(lon_ntf_out[lon_nbr_out-1] == lon_ntf_out[lon_nbr_out]) lon_ntf_out[lon_nbr_out]=lon_crn_out[mpf.dst_grid_corners*lon_nbr_out-3L]; // NCO ll assert(lon_ntf_out[lon_nbr_out-1] != lon_ntf_out[lon_nbr_out]); lon_spn=lon_ntf_out[lon_nbr_out]-lon_ntf_out[0L]; for(idx=0L;idx<lat_nbr_out;idx++) lat_ntf_out[idx]=lat_crn_out[mpf.dst_grid_corners*idx]; if(flg_s2n) lat_ntf_out[lat_nbr_out]=max_dbl(lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-1L],lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-2L]); else lat_ntf_out[lat_nbr_out]=min_dbl(lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-1L],lat_crn_out[mpf.dst_grid_corners*lat_nbr_out-2L]); assert(lat_ntf_out[lat_nbr_out] != lat_ntf_out[lat_nbr_out-1]); lat_spn=fabs(lat_ntf_out[lat_nbr_out]-lat_ntf_out[0L]); /* Place 1-D rectangular interfaces into 2-D coordinate boundaries */ for(idx=0L;idx<lon_nbr_out;idx++){ lon_bnd_out[2L*idx]=lon_ntf_out[idx]; lon_bnd_out[2L*idx+1L]=lon_ntf_out[idx+1L]; } /* !lon_nbr_out */ for(idx=0L;idx<lat_nbr_out;idx++){ lat_bnd_out[2L*idx]=lat_ntf_out[idx]; lat_bnd_out[2L*idx+1L]=lat_ntf_out[idx+1L]; } /* !lat_nbr_out */ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0L;idx<lon_nbr_out;idx++) (void)fprintf(stdout,"lon[%li] = [%g, %g, %g]\n",idx,lon_bnd_out[2L*idx],lon_ctr_out[idx],lon_bnd_out[2L*idx+1L]); for(idx=0L;idx<lat_nbr_out;idx++) (void)fprintf(stdout,"lat[%li] = [%g, %g, %g]\n",idx,lat_bnd_out[2L*idx],lat_ctr_out[idx],lat_bnd_out[2L*idx+1L]); } /* endif dbg */ /* Global or regional grid? */ nco_grd_xtn_enm nco_grd_xtn; /* [enm] Extent of grid */ if((float)lon_spn == 360.0f && (float)lat_spn == 180.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; /* Diagnose type of latitude output grid by testing second latitude center against formulae */ double lat_ctr_tst_eqa; double lat_ctr_tst_fv; if(flg_s2n) lat_ctr_tst_eqa=lat_ntf_out[0L]+lat_spn*1.5/lat_nbr_out; else lat_ctr_tst_eqa=lat_ntf_out[0L]-lat_spn*1.5/lat_nbr_out; if(flg_s2n) lat_ctr_tst_fv=lat_ntf_out[0L]+lat_spn/(lat_nbr_out-1L); else lat_ctr_tst_fv=lat_ntf_out[0L]-lat_spn/(lat_nbr_out-1L); double lat_ctr_tst_gss; /* In diagnosing grids, agreement to slightly worse than single-precision is "good enough for government work" Hence some comparisons cast from double to float before comparison 20150526: T42 grid from SCRIP and related maps, and NCL-generated Gaussian grids for CESM, are accurate to at most ~eight digits 20150611: map_ne120np4_to_fv801x1600_bilin.150418.nc has yc_b[1600]=-89.775000006 not expected exact value lat_ctr[1]=-89.775000000000006 20170521: T62 grid from NCEP-NCAR Reanalysis 1 is worse than single precision, has yc_[192]=-86.6531 not expected exact value lat_ctr[1]=-86.6532 */ if((float)lat_ctr_out[1L] == (float)lat_ctr_tst_eqa) nco_grd_lat_typ=nco_grd_lat_eqa; if((float)lat_ctr_out[1L] == (float)lat_ctr_tst_fv) nco_grd_lat_typ=nco_grd_lat_fv; double *wgt_Gss_out=NULL; // [frc] Gaussian weights double precision if(nco_grd_lat_typ == nco_grd_lat_nil){ /* Check for Gaussian grid */ double *lat_sin_out; // [frc] Sine of Gaussian latitudes double precision lat_sin_out=(double *)nco_malloc(lat_nbr_out*sizeof(double)); wgt_Gss_out=(double *)nco_malloc(lat_nbr_out*sizeof(double)); (void)nco_lat_wgt_gss(lat_nbr_out,flg_s2n,lat_sin_out,wgt_Gss_out); lat_ctr_tst_gss=rdn2dgr*asin(lat_sin_out[1L]); /* Gaussian weights on output grid will be double-precision accurate Grid itself is kept as user-specified so area diagnosed by ESMF_RegridWeightGen may be slightly inconsistent with weights */ if(nco_dbg_lvl_get() >= nco_dbg_sbr) (void)fprintf(stderr,"%s: INFO %s reports lat_ctr_out[1] = %g, lat_ctr_tst_gss = %g\n",nco_prg_nm_get(),fnc_nm,lat_ctr_out[1L],lat_ctr_tst_gss); if((float)lat_ctr_out[1L] == (float)lat_ctr_tst_gss) nco_grd_lat_typ=nco_grd_lat_gss; if(lat_sin_out) lat_sin_out=(double *)nco_free(lat_sin_out); } /* !Gaussian */ if(nco_grd_lat_typ == nco_grd_lat_nil){ /* If still of unknown type, this 2D grid may be weird This occurs, e.g., with POP3 destination grid Change gridtype from nil (which means not-yet-set) to unknown (which means none of the others matched) */ nco_grd_lat_typ=nco_grd_lat_unk; } /* !nil */ /* Currently grd_lat_typ and grd_2D_typ are equivalent, though that may be relaxed in future */ if(nco_grd_lat_typ == nco_grd_lat_unk) nco_grd_2D_typ=nco_grd_2D_unk; else if(nco_grd_lat_typ == nco_grd_lat_gss) nco_grd_2D_typ=nco_grd_2D_gss; else if(nco_grd_lat_typ == nco_grd_lat_fv) nco_grd_2D_typ=nco_grd_2D_fv; else if(nco_grd_lat_typ == nco_grd_lat_eqa) nco_grd_2D_typ=nco_grd_2D_eqa; else assert(False); if(nco_grd_lon_typ == nco_grd_lon_nil){ /* NB: Longitude grid diagnosis is susceptible to mistakes when input mapfile embeds common faulty grids, e.g., ACME *150418* FV maps map_ne30np4_to_fv129x256_aave.150418.nc is diagnosed as regional grid of unknown type because of input grid flaws map_ne30np4_to_fv129x256_aave.20150901.nc is (correctly) diagnosed as global grid of with lon_Grn_ctr */ if( (float)lon_ctr_out[0L] == 0.0f && (float)lon_ctr_out[1L] == (float)(lon_ctr_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_Grn_ctr; else if((float)lon_ctr_out[0L] == -180.0f && (float)lon_ctr_out[1L] == (float)(lon_ctr_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_180_ctr; else if((float)lon_ntf_out[0L] == 0.0f && (float)lon_ntf_out[1L] == (float)(lon_ntf_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_Grn_wst; else if((float)lon_ntf_out[0L] == -180.0f && (float)lon_ntf_out[1L] == (float)(lon_ntf_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_180_wst; else if((float)lon_ctr_out[1L] == (float)(lon_ctr_out[0L]+lon_spn/lon_nbr_out)) nco_grd_lon_typ=nco_grd_lon_bb; else nco_grd_lon_typ=nco_grd_lon_unk; } /* !nco_grd_lon_typ */ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s diagnosed output latitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lat_sng(nco_grd_lat_typ)); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s diagnosed output longitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lon_sng(nco_grd_lon_typ)); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO %s diagnosed output grid-extent: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_xtn_sng(nco_grd_xtn)); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ slat_ctr_out=(double *)nco_malloc(slat_nbr_out*nco_typ_lng(crd_typ_out)); slat_wgt_out=(double *)nco_malloc(slat_nbr_out*nco_typ_lng(crd_typ_out)); slon_ctr_out=(double *)nco_malloc(slon_nbr_out*nco_typ_lng(crd_typ_out)); for(idx=0L;idx<slat_nbr_out;idx++){ slat_ctr_out[idx]=lat_ntf_out[idx+1L]; slat_wgt_out[idx]=fabs(sin(dgr2rdn*lat_ctr_out[idx+1L])-sin(dgr2rdn*lat_ctr_out[idx])); /* fabs() ensures positive area in n2s grids */ } /* !lat_nbr_out */ for(idx=0L;idx<slon_nbr_out;idx++){ slon_ctr_out[idx]=lon_ntf_out[idx]; } /* !lat_nbr_out */ } /* !nco_grd_lat_fv */ switch(nco_grd_lat_typ){ case nco_grd_lat_eqa: case nco_grd_lat_fv: for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_out[idx]=fabs(sin(dgr2rdn*lat_bnd_out[2*idx+1L])-sin(dgr2rdn*lat_bnd_out[2*idx])); /* fabs() ensures positive area in n2s grids */ break; case nco_grd_lat_gss: for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_out[idx]=wgt_Gss_out[idx]; if(wgt_Gss_out) wgt_Gss_out=(double *)nco_free(wgt_Gss_out); break; case nco_grd_lat_unk: for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_out[idx]=0.0; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: WARNING %s reports unknown output latitude grid-type. Unable to guess what latitude weights should be.\n",nco_prg_nm_get(),fnc_nm); break; default: nco_dfl_case_generic_err(); break; } /* end nco_grd_lat_typ switch */ /* Fuzzy test of latitude weight normalization */ lat_wgt_ttl=0.0; for(idx=0L;idx<lat_nbr_out;idx++) lat_wgt_ttl+=lat_wgt_out[idx]; if(nco_grd_lat_typ == nco_grd_lat_eqa || nco_grd_lat_typ == nco_grd_lat_fv){ double lat_wgt_ttl_xpc; /* [frc] Expected sum of latitude weights */ lat_wgt_ttl_xpc=fabs(sin(dgr2rdn*lat_bnd_out[2L*(lat_nbr_out-1L)+1L])-sin(dgr2rdn*lat_bnd_out[0L])); /* fabs() ensures positive area in n2s grids */ assert(fabs(1.0-lat_wgt_ttl/lat_wgt_ttl_xpc) < eps_rlt); if(lat_wgt_ttl_xpc < 0.0) abort(); /* CEWI Use lat_wgt_ttl_xpc at least once outside of assert() to avoid gcc 4.8.2 set-but-not-used warning */ } /* !nco_grd_lat_eqa, !nco_grd_lat_fv */ } /* !flg_grd_out_rct */ /* When possible, ensure area_out is non-zero 20150722: ESMF documentation says "The grid area array is only output when the conservative remapping option is used" Actually, ESMF does (always?) output area, but area == 0.0 unless conservative remapping is used 20150721: ESMF bilinear interpolation map ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.150418.nc has area == 0.0 20150710: Tempest regionally refined grids like bilinearly interpolated CONUS for ACME RRM has area_out == 0 20150821: ESMF always outputs area_out == 0.0 for bilinear interpolation Check whether NCO must diagnose and provide its own area_out */ /* If area_out contains any zero... */ for(idx=0;idx<(long)grd_sz_out;idx++) if(area_out[idx] == 0.0) break; if(idx != (long)grd_sz_out){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Output grid detected with zero-valued output area(s) at idx = %ld (and likely others, too).\n",nco_prg_nm_get(),idx); } /* !zero */ for(idx=0;idx<(long)grd_sz_out;idx++) if(area_out[idx] != 0.0) break; if(idx == (long)grd_sz_out){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports area_out from mapfile is everywhere zero. This is expected for bilinearly interpolated output maps produced by ESMF_RegridWeightGen. ",nco_prg_nm_get(),fnc_nm); if(flg_grd_out_2D && flg_grd_out_rct && (bnd_nbr_out == 2 || bnd_nbr_out == 4)){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"Since the destination grid provides cell bounds information, NCO will diagnose area (and output it as a variable named \"%s\") from the destination gridcell boundaries. NCO diagnoses quadrilateral area for rectangular output grids from a formula that assumes that cell boundaries follow arcs of constant latitude and longitude. This differs from the area of cells with boundaries that follow great circle arcs (used by, e.g., ESMF_RegridWeightGen and TempestRemap). Be warned that NCO correctly diagnoses area for all convex polygons, yet not for most concave polygons. To determine whether the diagnosed areas are fully consistent with the output grid, one must know such exact details. If your grid has analytic areas that NCO does not yet diagnose correctly from provided cell boundaries, please contact us.\n",rgr->area_nm); flg_dgn_area_out=True; }else if(flg_grd_out_2D && flg_grd_out_crv && (bnd_nbr_out == 2 || bnd_nbr_out == 4)){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"Since the destination grid provides cell bounds information, NCO will diagnose area (and output it as a variable named \"%s\") from the destination gridcell boundaries. NCO diagnoses quadrilateral area for curvilinear output grids from formulae that assume that cell boundaries follow great circle arcs (as do, e.g., ESMF_RegridWeightGen and TempestRemap). This differs from the area of cells with boundaries that follow lines of constant latitude or longitude. Be warned that NCO correctly diagnoses area for all convex polygons, yet not for most concave polygons. To determine whether the diagnosed areas are fully consistent with the output grid, one must know such exact details. If your grid has analytic areas that NCO does not yet diagnose correctly from provided cell boundaries, please contact us.\n",rgr->area_nm); flg_dgn_area_out=True; }else if(flg_grd_out_1D && flg_bnd_1D_usable){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"Since the destination grid provides cell bounds information, NCO will diagnose area (and output it as a variable name \"%s\") from the destination gridcell boundaries. NCO diagnoses spherical polygon area for unstructured output grids from formulae that assume that cell boundaries follow great circle arcs (as do, e.g., ESMFRegridWeightGen and TempestRemap). This differs from the area of cells with boundaries that follow lines of constant latitude or longitude. Be warned that NCO correctly diagnoses area for all convex polygons, yet not for most concave polygons. To determine whether the diagnosed areas are fully consistent with the output grid, one must know such exact details. If your grid has analytic areas that NCO does not yet diagnose correctly from provided cell boundaries, please contact us.\n",rgr->area_nm); flg_dgn_area_out=True; }else{ /* !1D */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"However, NCO cannot find enough boundary information, or it is too stupid about spherical trigonometry, to diagnose area_out. NCO will output an area variable (named \"%s\") copied from the input mapfile. This area will be everywhere zero.\n",rgr->area_nm); } /* !2D */ } /* !area */ if(flg_dgn_area_out){ if(flg_grd_out_1D && flg_bnd_1D_usable){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"INFO: Diagnosing area_out for 1D grid\n"); /* Area of unstructured grids requires spherical trigonometry */ nco_sph_plg_area(rgr,lat_bnd_out,lon_bnd_out,col_nbr_out,bnd_nbr_out,area_out); } /* !1D */ if(flg_grd_out_crv){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"INFO: Diagnosing area_out for curvilinear grid\n"); /* Area of curvilinear grids requires spherical trigonometry */ nco_sph_plg_area(rgr,lat_crn_out,lon_crn_out,grd_sz_out,bnd_nbr_out,area_out); } /* !flg_grd_out_crv */ if(flg_grd_out_rct && nco_grd_2D_typ != nco_grd_2D_unk){ /* Mr. Enenstein and George O. Abell taught me the area of spherical zones Spherical zone area is exact and faithful to underlying rectangular equi-angular grid However, ESMF and Tempest approximate spherical polygons as connected by great circle arcs fxm: Distinguish spherical zone shapes (e.g., equi-angular) from great circle arcs (e.g., unstructured polygons) */ for(lat_idx=0;lat_idx<lat_nbr_out;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr_out;lon_idx++) area_out[lat_idx*lon_nbr_out+lon_idx]=fabs(dgr2rdn*(lon_bnd_out[2*lon_idx+1]-lon_bnd_out[2*lon_idx])*(sin(dgr2rdn*lat_bnd_out[2*lat_idx+1])-sin(dgr2rdn*lat_bnd_out[2*lat_idx]))); /* fabs() ensures positive area in n2s grids */ } /* !spherical zones */ } /* !flg_dgn_area_out */ if(rgr->tst == -1){ /* Passing --rgr tst=-1 causes regridder to fail here This failure should cause host climo script to abort */ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports regridder instructed to fail here. This tests failure mode in climo scripts...\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !tst */ /* Verify that frc_out is sometimes non-zero ESMF: "The grid frac arrays (frac_a and frac_b) are calculated by ESMF_RegridWeightGen. For conservative remapping, the grid frac array returns the area fraction of the grid cell which participates in the remapping. For bilinear and patch remapping, the destination grid frac array [frac_b] is one where the grid point participates in the remapping and zero otherwise. For bilinear and patch remapping, the source grid frac array is always set to zero." SCRIP: Similar to ESMF For both ESMF+SCRIP frac_[ab] are computed by the weight-generation algorithm and are not specified as part of the input grids How does an input ocean grid indicate that, say, half the gridcell is land and half ocean? Does it use the area variable to tell the weight generation algorithm that a gridcell is fractional? In other words does it use grid_imask=1 and grid_area=0.5*full_gridcell_area and, e.g., T=273.0? */ for(idx=0;idx<(long)grd_sz_out;idx++) if(frc_out[idx] != 0.0) break; if(idx == (long)grd_sz_out){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports frc_out == frac_b contains all zeros\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !always zero */ /* Test whether frc_out is ever zero... */ for(idx=0;idx<(long)grd_sz_out;idx++) if(frc_out[idx] == 0.0) break; if(nco_dbg_lvl_get() >= nco_dbg_std) if(idx != (long)grd_sz_out) (void)fprintf(stdout,"%s: INFO %s reports frc_out == frac_b contains zero-elements (e.g., at 1D idx = %ld)\n",nco_prg_nm_get(),fnc_nm,idx); /* Normalizing by frc_out is redundant iff frc_out == 1.0, so we can save time without sacrificing accuracy However, frc_out is often (e.g., for CS <-> RLL maps) close but not equal to unity (ESMF_RegridWeightGen issue?) Hence, decide whether to normalize by frc_out by diagnosing the furthest excursion of frc_out from unity */ nco_bool flg_frc_out_one=True; /* [flg] Destination gridcell fraction frc_out == frac_b is in [1-epsilon,frc_out,1+epsilon] */ nco_bool flg_frc_out_wrt=False; /* [flg] Write destination gridcell fraction frc_out == frac_b to regridded files */ double frc_out_dff_one; /* [frc] Deviation of frc_out from 1.0 */ double frc_out_dff_one_max=0.0; /* [frc] Maximum deviation of frc_out from 1.0 */ long idx_max_dvn; /* [idx] Index of maximum deviation from 1.0 */ for(idx=0;idx<(long)grd_sz_out;idx++){ frc_out_dff_one=fabs(frc_out[idx]-1.0); if(frc_out_dff_one > frc_out_dff_one_max){ frc_out_dff_one_max=frc_out_dff_one; idx_max_dvn=idx; } /* !max */ } /* !idx */ if(frc_out_dff_one_max > eps_rlt) flg_frc_out_one=False; nco_bool flg_frc_nrm=False; /* [flg] Must normalize by frc_out == frac_b because frc_out is not always unity and specified normalization is destarea or none */ if(!flg_frc_out_one && /* If fraction is sometimes "far" from 1.0 and ... */ ((nco_rgr_mpf_typ == nco_rgr_mpf_ESMF && nco_rgr_mth_typ == nco_rgr_mth_conservative && (nco_rgr_nrm_typ == nco_rgr_nrm_destarea || nco_rgr_nrm_typ == nco_rgr_nrm_none)) || /* ESMF map-file specifies conservative regridding with "destarea" or "none" or ... */ (nco_rgr_mpf_typ != nco_rgr_mpf_ESMF)) /* 20191003: Weight-generator does not adhere to ESMF "normalization type" convention */ && True){ flg_frc_nrm=True; /* Avoid writing frc_out unless discrepancies are particularly egregious Otherwise would frc_out for standard remaps like ne30->fv129x256 for which eps=2.46e-13 */ double eps_rlt_wrt_thr=3.0e-13; /* 20181104: Never write frac_b for CMIP6! */ /* if(frc_out_dff_one_max > eps_rlt_wrt_thr) flg_frc_out_wrt=True; */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s reports global metadata specifies conservative remapping with normalization of type = %s. Furthermore, destination fractions frc_dst = dst_frac = frac_b = frc_out contain non-unity elements (maximum deviation from unity of %g exceeds hard-coded (in variable eps_rlt) relative-epsilon threshold of %g for frc_out[%ld] = %g). Thus normalization issues will be explicitly treated. Will apply \'destarea\' normalization (i.e., divide by non-zero frc_out[dst_idx]) to all regridded arrays.\n",nco_prg_nm_get(),fnc_nm,nco_rgr_nrm_sng(nco_rgr_nrm_typ),frc_out_dff_one_max,eps_rlt,idx_max_dvn,frc_out[idx_max_dvn]); if(nco_dbg_lvl_get() >= nco_dbg_std && flg_frc_out_wrt) (void)fprintf(stdout,"%s: INFO %s Maximum deviation %g exceeds threshold of %g that triggers automatic writing of fractional destination area as variable named frac_b in regridded output.\n",nco_prg_nm_get(),fnc_nm,frc_out_dff_one_max,eps_rlt_wrt_thr); } /* !sometimes non-unity */ if(nco_dbg_lvl_get() >= nco_dbg_std && flg_frc_nrm && rgr->flg_rnr){ // 20190918: Weaken from WARNING to INFO because NCO no longer renormalizes when using "destarea" maps unless specifically requested to with --rnr_thr (void)fprintf(stdout,"%s: INFO %s reports manual request to renormalize partially overlapped destination gridcells (i.e., gridcells with non-unity frc_dst = dst_frac = frac_b) to preserve mean-value of valid fraction of source gridcells (usually most useful for state variables), rather than dilute valid-fraction mean over total destination gridcell area to preserve area-integral of source data (the default, often most useful for ensuring global conservation of fluxes).\n",nco_prg_nm_get(),fnc_nm); //(void)fprintf(stdout,"%s: INFO %s reports manual request (with --rnr) to renormalize fields with non-unity frc_dst = dst_frac = frac_b at same time global metadata specifies normalization type = %s. Normalizing twice can be an error, depending on intent of each. Charlie is all ears on how NCO should handle this :)\n",nco_prg_nm_get(),fnc_nm,nco_rgr_nrm_sng(nco_rgr_nrm_typ)); //nco_exit(EXIT_FAILURE); } /* !flg_rnr */ /* Detailed summary of 2D grids now available including quality-checked coordinates and area */ if(flg_grd_out_2D && nco_dbg_lvl_get() >= nco_dbg_sbr){ lat_wgt_ttl=0.0; area_out_ttl=0.0; if(flg_grd_out_rct){ (void)fprintf(stderr,"%s: INFO %s reports destination rectangular latitude grid:\n",nco_prg_nm_get(),fnc_nm); for(idx=0;idx<lat_nbr_out;idx++) lat_wgt_ttl+=lat_wgt_out[idx]; } /* !flg_grd_out_rct */ for(lat_idx=0;lat_idx<lat_nbr_out;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr_out;lon_idx++) area_out_ttl+=area_out[lat_idx*lon_nbr_out+lon_idx]; (void)fprintf(stdout,"lat_wgt_ttl = %20.15f, frc_lat_wgt = %20.15f, area_ttl = %20.15f, frc_area = %20.15f\n",lat_wgt_ttl,lat_wgt_ttl/2.0,area_out_ttl,area_out_ttl/(4.0*M_PI)); if(flg_grd_out_rct){ for(idx=0;idx<lon_nbr_out;idx++) (void)fprintf(stdout,"lon[%li] = [%g, %g, %g]\n",idx,lon_bnd_out[2*idx],lon_ctr_out[idx],lon_bnd_out[2*idx+1]); for(idx=0;idx<lat_nbr_out;idx++) (void)fprintf(stdout,"lat[%li] = [%g, %g, %g]\n",idx,lat_bnd_out[2*idx],lat_ctr_out[idx],lat_bnd_out[2*idx+1]); for(idx=0;idx<lat_nbr_out;idx++) (void)fprintf(stdout,"lat[%li], wgt[%li] = %20.15f, %20.15f\n",idx,idx,lat_ctr_out[idx],lat_wgt_out[idx]); } /* !flg_grd_out_rct */ if(nco_dbg_lvl_get() > nco_dbg_crr) for(lat_idx=0;lat_idx<lat_nbr_out;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr_out;lon_idx++) (void)fprintf(stdout,"lat[%li] = %g, lon[%li] = %g, area[%li,%li] = %g\n",lat_idx,lat_ctr_out[lat_idx],lon_idx,lon_ctr_out[lon_idx],lat_idx,lon_idx,area_out[lat_idx*lon_nbr_out+lon_idx]); assert(area_out_ttl > 0.0); assert(area_out_ttl <= 4.0*M_PI + 5.0e-15); } /* !flg_grd_out_2D && !dbg */ /* Allocate space for and obtain weights and addresses */ wgt_raw=(double *)nco_malloc_dbg(mpf.num_links*nco_typ_lng(NC_DOUBLE),fnc_nm,"Unable to malloc() value buffer for remapping weights"); col_src_adr=(int *)nco_malloc_dbg(mpf.num_links*nco_typ_lng(NC_INT),fnc_nm,"Unable to malloc() value buffer for remapping addresses"); row_dst_adr=(int *)nco_malloc_dbg(mpf.num_links*nco_typ_lng(NC_INT),fnc_nm,"Unable to malloc() value buffer for remapping addresses"); /* Obtain remap matrix addresses and weights from map file */ dmn_srt[0]=0L; dmn_cnt[0]=mpf.num_links; rcd=nco_get_vara(in_id,col_src_adr_id,dmn_srt,dmn_cnt,col_src_adr,NC_INT); rcd=nco_get_vara(in_id,row_dst_adr_id,dmn_srt,dmn_cnt,row_dst_adr,NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=mpf.num_links; if(nco_rgr_mpf_typ != nco_rgr_mpf_SCRIP){ rcd=nco_get_vara(in_id,wgt_raw_id,dmn_srt,dmn_cnt,wgt_raw,NC_DOUBLE); }else{ /* SCRIP mapfiles store 2D weight array remap_matrix[num_links,num_wgts] Apply only first weight for first-order conservative accuracy (i.e., area overlap) Apply all three weights for second-order conservative accuracy (by including gradients from centroid to vertices) */ dmn_srd[0]=1L; dmn_srt[1]=0L; dmn_cnt[1]=1L; dmn_srd[1]=mpf.num_wgts; rcd=nco_get_vars(in_id,wgt_raw_id,dmn_srt,dmn_cnt,dmn_srd,wgt_raw,NC_DOUBLE); } /* !SCRIP */ /* Pre-subtract one from row/column addresses (stored, by convention, as Fortran indices) to optimize later access with C indices */ size_t lnk_nbr; /* [nbr] Number of links */ size_t lnk_idx; /* [idx] Link index */ lnk_nbr=mpf.num_links; for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) row_dst_adr[lnk_idx]--; for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) col_src_adr[lnk_idx]--; if(nco_dbg_lvl_get() >= nco_dbg_io){ (void)fprintf(stdout,"idx row_dst col_src wgt_raw\n"); for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) (void)fprintf(stdout,"%li %d %d %g\n",lnk_idx,row_dst_adr[lnk_idx],col_src_adr[lnk_idx],wgt_raw[lnk_idx]); } /* endif dbg */ /* Free memory associated with input file */ if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt) dmn_cnt=(long *)nco_free(dmn_cnt); if(dmn_srd) dmn_srd=(long *)nco_free(dmn_srd); /* Close input netCDF file */ nco_close(in_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); /* Above this line, fl_in and in_id refer to map file Below this line, fl_in and in_id refer to input file to be regridded */ /* Initialize */ in_id=rgr->in_id; out_id=rgr->out_id; /* Sanity check that input data file matches expectations from mapfile */ char *col_nm_in=rgr->col_nm_in; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ char *lat_nm_in=rgr->lat_nm_in; /* [sng] Name of input dimension to recognize as latitude */ char *lon_nm_in=rgr->lon_nm_in; /* [sng] Name of input dimension to recognize as longitude */ int dmn_id_col=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lat; /* [id] Dimension ID */ int dmn_id_lon; /* [id] Dimension ID */ /* 20160503 Discover coordinates via CF Convention if indicated This copies method used in nco_grd_nfr() */ /* Begin CF-coordinates block */ cf_crd_sct *cf=NULL; char *rgr_var; /* [sng] Variable for special regridding treatment */ nco_bool flg_cf=False; /* [flg] Follow CF Coordinates convention to find and infer grid */ rgr_var=rgr->var_nm; if(rgr_var){ /* Infer grid from special variable Intended to be variable that has both horizontal dimensions and "coordinates" attribute, e.g., ncks --cdl -m ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc | grep coordinates 4LFTX_221_SPDY_S113:coordinates = "gridlat_221 gridlon_221" ; Usage: ncks -O -D 3 --rgr infer --rgr_var=ALBDO_221_SFC_S113 --rgr grid=${HOME}/grd_narr.nc ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc ~/foo.nc */ char crd_sng[]="coordinates"; /* CF-standard coordinates attribute name */ cf=(cf_crd_sct *)nco_malloc(sizeof(cf_crd_sct)); cf->crd=False; /* [flg] CF coordinates information is complete */ cf->crd_id[0]=NC_MIN_INT; /* [id] Coordinate ID, first */ cf->crd_id[1]=NC_MIN_INT; /* [id] Coordinate ID, second */ cf->crd_nm[0]=NULL; /* [sng] Coordinate name, first */ cf->crd_nm[1]=NULL; /* [sng] Coordinate name, second */ cf->crd_sng=NULL; /* [sng] Coordinates attribute value */ cf->dmn_id[0]=NC_MIN_INT; /* [id] Dimension ID, first */ cf->dmn_id[1]=NC_MIN_INT; /* [id] Dimension ID, second */ cf->dmn_nm[0]=NULL; /* [sng] Dimension name, first */ cf->dmn_nm[1]=NULL; /* [sng] Dimension name, second */ cf->unt_sng[0]=NULL; /* [sng] Units string, first coordinate */ cf->unt_sng[1]=NULL; /* [sng] Units string, second coordinate */ cf->var_id=NC_MIN_INT; /* [id] Coordinate variable ID */ cf->var_nm=NULL; /* [sng] Coordinates variable name */ cf->var_type=NC_NAT; /* [enm] Coordinates variable type */ if((rcd=nco_inq_varid_flg(in_id,rgr_var,&cf->var_id)) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports special \"coordinates\" variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd */ cf->crd_sng=nco_char_att_get(in_id,cf->var_id,crd_sng); if(cf->crd_sng){ cf->crd=True; }else{ /* !rcd && att_typ */ (void)fprintf(stderr,"%s: WARNING %s reports coordinates variable %s does not have character-valued \"coordinates\" attribute. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd && att_typ */ /* Valid coordinates attribute requires two coordinate names separated by space character */ char *crd_nm[NCO_MAX_CRD_PER_VAR]; /* [sng] Coordinate name start position */ char *crd_dpl; /* [sng] Modifiable duplicate of coordinates string */ char *spc_ptr; /* [sng] Pointer to space character (' ') */ int crd_nbr=0; /* [nbr] Number of names in coordinates attribute */ int crd_spt=0; /* [nbr] Number of "spatial-like" (that include "degree" in units) coordinates */ int crd_idx=0; /* [idx] Counter for coordinate names */ for(crd_idx=0;crd_idx<NCO_MAX_CRD_PER_VAR;crd_idx++) crd_nm[crd_idx]=NULL; crd_dpl=(char *)strdup(cf->crd_sng); /* Search for spaces starting from end of string */ while((spc_ptr=strrchr(crd_dpl,' '))){ crd_nm[crd_nbr]=spc_ptr+1L; crd_nbr++; /* NUL-terminate so next search ends here */ *spc_ptr='\0'; } /* !sbs_ptr */ /* Final coordinate name begins where coordinate string starts */ crd_nm[crd_nbr]=crd_dpl; /* Change crd_nbr from 0-based index to actual coordinate number */ crd_nbr++; if(crd_nbr < 2){ (void)fprintf(stderr,"%s: WARNING %s found only %d coordinate(s) in \"coordinates\" attribute \"%s\", at least two are required. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,crd_nbr,cf->crd_sng); goto skp_cf; } /* !crd_nbr */ /* If more than two coordinate names are present, choose first two (searching backwards from end) with "degree" in units attributes, otherwise just choose first two */ crd_idx=crd_spt=0; while(crd_spt < 2 && crd_idx < crd_nbr){ cf->crd_nm[crd_spt]=crd_nm[crd_idx]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[crd_spt],&cf->crd_id[crd_spt])) == NC_NOERR){ cf->unt_sng[crd_spt]=nco_char_att_get(in_id,cf->crd_id[crd_spt],unt_sng); if(cf->unt_sng[crd_spt]){ if(strcasestr(cf->unt_sng[crd_spt],"degree")){ /* Increment count of spatial-like coordinates... */ crd_spt++; }else{ /* ...or free() memory allocated during search */ cf->unt_sng[crd_spt]=(char *)nco_free(cf->unt_sng[crd_spt]); } /* !strcasestr() */ crd_idx++; } /* !rcd && att_typ */ } /* !rcd */ } /* !crd_spt */ /* If while()-loop above was successful, our search is over Otherwise, use first two coordinate names regardless of units, and print more diagnostics */ if(crd_spt < 2){ cf->crd_nm[0]=crd_nm[0]; cf->crd_nm[1]=crd_nm[1]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[0],&cf->crd_id[0])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s not found. Turning-off CF coordinates search for this file.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0]); goto skp_cf; } /* !rcd */ if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[1],&cf->crd_id[1])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s not found. Turning-off CF coordinates search for this file.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1]); goto skp_cf; } /* !rcd */ cf->unt_sng[0]=nco_char_att_get(in_id,cf->crd_id[0],unt_sng); if(cf->unt_sng[0]){ if(!strcasestr(cf->unt_sng[0],"degrees_")) (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->unt_sng[0]); } /* !rcd && att_typ */ cf->unt_sng[1]=nco_char_att_get(in_id,cf->crd_id[1],unt_sng); if(cf->unt_sng[1]){ if(!strcasestr(cf->unt_sng[1],"degrees_")) (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1],cf->unt_sng[1]); } /* !rcd && att_typ */ } /* !crd_spt */ int crd_rnk; /* [nbr] Coordinate rank */ rcd=nco_inq_varndims(in_id,cf->crd_id[0],&crd_rnk); if(crd_rnk != 2){ (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s has %i dimension(s). Skipping CF coordinates method.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],crd_rnk); goto skp_cf; } /* !crd_rnk */ rcd=nco_inq_vardimid(in_id,cf->crd_id[0],cf->dmn_id); cf->dmn_nm[0]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); cf->dmn_nm[1]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); rcd=nco_inq_dimname(in_id,cf->dmn_id[0],cf->dmn_nm[0]); rcd=nco_inq_dimname(in_id,cf->dmn_id[1],cf->dmn_nm[1]); /* "coordinates" convention does not guarantee lat, lon are specified in that order Use "units" values, if any, to determine order In absence of "units", assume order is lat, lon */ nco_bool crd0_is_lat=False; /* [flg] First coordinate is latitude */ nco_bool crd0_is_lon=False; /* [flg] First coordinate is longitude */ nco_bool crd1_is_lat=False; /* [flg] Second coordinate is latitude */ nco_bool crd1_is_lon=False; /* [flg] Second coordinate is longitude */ if(cf->unt_sng[0]){ if(!strcasecmp(cf->unt_sng[0],"degrees_north")) crd0_is_lat=True; if(!strcasecmp(cf->unt_sng[0],"degrees_east")) crd0_is_lon=True; } /* endif */ if(cf->unt_sng[1]){ if(!strcasecmp(cf->unt_sng[1],"degrees_north")) crd1_is_lat=True; if(!strcasecmp(cf->unt_sng[1],"degrees_east")) crd1_is_lon=True; } /* endif */ assert((crd0_is_lat && crd1_is_lon) || (crd0_is_lon && crd1_is_lat)); int idx_lat; int idx_lon; if(crd0_is_lat && crd1_is_lon){ idx_lat=0; idx_lon=1; }else{ idx_lat=1; idx_lon=0; } /* endif */ /* Dimensions and coordinates have been vetted. Store as primary lookup names. Dimensions are always returned in order [LRV,MRV]=[0,1] LRV is along-track direction, and MRV is across-track (at least in NASA data) Internally we label LRV as "lat" and MRV as "lon" so that code looks similar for curvilinear and rectangular grids */ dmn_id_lat=cf->dmn_id[0]; dmn_id_lon=cf->dmn_id[1]; /* Subtlety: lat_nm_in is coordinate (variable+dimension) name when specified from command-line (as in nco_grd_nfr()), dimension name when found through CF-method (as in nco_rgr_wgt()). This confusing distinction could be avoided by passing command-line dimension names through-to nco_rgr_wgt(). However, that route would require complex priorities for what to do when passing command-line coordinate names not dimension names and visa-versa. */ lat_nm_in=strdup(cf->dmn_nm[0]); lon_nm_in=strdup(cf->dmn_nm[1]); //lat_nm_in=strdup(cf->crd_nm[idx_lat]); //lon_nm_in=strdup(cf->crd_nm[idx_lon]); /* Next four lines unnecessary in nco_rgr_wgt() which only needs dimension names (it reads input coordinates from map-file not data-file) */ //lat_ctr_id=cf->crd_id[idx_lat]; //lon_ctr_id=cf->crd_id[idx_lon]; //lat_dmn_nm=strdup(cf->dmn_nm[0]); //lon_dmn_nm=strdup(cf->dmn_nm[1]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s \"coordinates\" attribute \"%s\" points to coordinates %s and %s. Latitude coordinate \"%s\" has dimensions \"%s\" and \"%s\". Longitude coordinate \"%s\" has dimensions \"%s\" and \"%s\".\n",nco_prg_nm_get(),fnc_nm,rgr_var,cf->crd_sng,cf->crd_nm[0],cf->crd_nm[1],cf->crd_nm[idx_lat],cf->dmn_nm[idx_lat],cf->dmn_nm[idx_lon],cf->crd_nm[idx_lon],cf->dmn_nm[idx_lat],cf->dmn_nm[idx_lon]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s Coordinates %s and %s \"units\" values are \"%s\" and \"%s\", respectively.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->crd_nm[1],cf->unt_sng[0] ? cf->unt_sng[0] : "(non-existent)",cf->unt_sng[1] ? cf->unt_sng[1] : "(non-existent)"); /* Clean-up CF coordinates memory */ if(crd_dpl) crd_dpl=(char *)nco_free(crd_dpl); if(cf->crd_sng) cf->crd_sng=(char *)nco_free(cf->crd_sng); if(cf->dmn_nm[0]) cf->dmn_nm[0]=(char *)nco_free(cf->dmn_nm[0]); if(cf->dmn_nm[1]) cf->dmn_nm[1]=(char *)nco_free(cf->dmn_nm[1]); if(cf->unt_sng[0]) cf->unt_sng[0]=(char *)nco_free(cf->unt_sng[0]); if(cf->unt_sng[1]) cf->unt_sng[1]=(char *)nco_free(cf->unt_sng[1]); // if(foo) foo=(char *)nco_free(foo); } /* !rgr_var */ /* goto skp_cf */ skp_cf: /* free() any abandoned cf structure now */ if(!flg_cf) if(cf) cf=(cf_crd_sct *)nco_free(cf); rcd=NC_NOERR; /* End CF-coordinates block */ if(flg_grd_in_1D){ long col_nbr_in_dat; /* [nbr] Number of columns in input datafile */ /* Check default or command-line option first, then search usual suspects, and if that fails then guess unstructured dimension is dimension in input file with size n_a expected by input map file, suggested by PJCS Using internal database names first ensures users can pick between multiple dimensions of size n_a 20180313: fxm New PJCS algorithm is superior, should eliminate internal database for unstructured grids? Database is necessary for 2D grids because otherwise no good way to disambiguate latitude from longitude */ if(col_nm_in && (rcd=nco_inq_dimid_flg(in_id,col_nm_in,&dmn_id_col)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"lndgrid",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("lndgrid"); /* CLM */ else if((rcd=nco_inq_dimid_flg(in_id,"nCells",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("nCells"); /* MPAS-O/I */ else if((rcd=nco_inq_dimid_flg(in_id,"nEdges",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("nEdges"); /* MPAS-O/I */ else if((rcd=nco_inq_dimid_flg(in_id,"ncol_d",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("ncol_d"); /* EAM dynamics grid */ else if((rcd=nco_inq_dimid_flg(in_id,"ncol_p",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("ncol_d"); /* EAM physics grid */ else if((rcd=nco_inq_dimid_flg(in_id,"sounding_id",&dmn_id_col)) == NC_NOERR) col_nm_in=strdup("sounding_id"); /* OCO2 */ /* 20180605: Database matches to above names may be false-positives ALM/CLM/CTSM/ELM store all possible dimension names that archived variables could use NCO only prints dimensions used in variables, while ncdump prints all dimensions From ncdump we find usually unused ALM/CLM/CTSM/ELM dimensions: gridcell, lndunit, column, pft, levurb, numrad, levsno Check that matched dimension has expected size: */ if(dmn_id_col != NC_MIN_INT){ rcd=nco_inq_dimlen(in_id,dmn_id_col,&col_nbr_in_dat); if(col_nbr_in != col_nbr_in_dat){ dmn_id_col=NC_MIN_INT; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s database-prioritized unstructured dimension candidate \"%s\" has size not expected by supplied map-file: mapfile col_nbr_in = %ld != %ld = col_nbr_in from datafile. HINT: Check that source grid (i.e., \"grid A\") used to create mapfile matches grid on which data are stored in input datafile.\n",nco_prg_nm_get(),fnc_nm,col_nm_in,col_nbr_in,col_nbr_in_dat); } /* !col_nbr_in */ }else{ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s expects data on an unstructured grid yet cannot find a dimension name that matches the usual suspects for unstructured dimensions (ncol, gridcell, lndgrid, nCells, nEdges, sounding_id). Consider specifying horizontal dimension name to ncks with \"--rgr col_nm=foo\" or to ncremap with \"ncremap -R '--rgr col_nm=foo'\", and consider requesting the NCO project to add this horizontal dimension name to its internal database.\n",nco_prg_nm_get(),fnc_nm); } /* !dmn_id_col */ if(dmn_id_col == NC_MIN_INT){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s Proceeding with fallback algorithm to guess unstructured dimension as first dimension in data file of equal size to that expected by supplied map-file...\n",nco_prg_nm_get(),fnc_nm); /* 20180312: Unstructured dimension must have same size as input map file, suggested by PJCS */ int *dmn_ids_in; /* [nbr] Input file dimension IDs */ int dmn_nbr_in; /* [nbr] Number of dimensions in input file */ const int flg_prn=0; /* [enm] Parent flag */ rcd=nco_inq_dimids(in_id,&dmn_nbr_in,NULL,flg_prn); dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); rcd=nco_inq_dimids(in_id,NULL,dmn_ids_in,flg_prn); /* Find dimension, if any, with same size as map "a" src_grid_dims[0] = n_a dimension */ for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ dmn_id_col=dmn_ids_in[dmn_idx]; rcd=nco_inq_dimlen(in_id,dmn_id_col,&col_nbr_in_dat); if(col_nbr_in == col_nbr_in_dat){ rcd=nco_inq_dimname(in_id,dmn_id_col,col_nm_in); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s found that dimension %s in datafile has same size (n_a = %ld) expected by map-file. Assuming %s is the unstructured dimension.\n",nco_prg_nm_get(),fnc_nm,col_nm_in,col_nbr_in,col_nm_in); break; } /* !col_nbr_in */ } /* !dmn_idx */ if(dmn_ids_in) dmn_ids_in=(int *)nco_free(dmn_ids_in); if(dmn_idx == dmn_nbr_in){ dmn_id_col=NC_MIN_INT; (void)fprintf(stdout,"%s: WARNING received a map-file constructed to process data on an unstructured (one-dimensional) grid, but %s (aka \"the regridder\") cannot find a dimension in the input data file (or, with ncremap, a possibly already subsetted intermediate file) that matches the size of the unstructured dimension in the supplied map-file = src_grd_dims[0] = n_a = %ld.\nHINT: Ensure at least one member of the variable extraction list has a spatial dimension of size = %ld\n",nco_prg_nm_get(),fnc_nm,col_nbr_in,col_nbr_in); (void)fprintf(stdout,"%s: INFO %s reports a third, last-ditch (aka \"Hail Mary\") workaround may work. The Hail-Mary allows logically 1D map-files to regrid logically 2D datasets, so long as the product of the horizontal dimension sizes in the 2D input data file equals the map-file 1D dimension size.\n",nco_prg_nm_get(),fnc_nm); /* Hail Mary algorithm: Use following 2D input grid block to identify horizontal coordinates and dimensions */ flg_grd_in_1D_dat_in_2D=True; flg_grd_in_2D=True; //nco_exit(EXIT_FAILURE); } /* !dmn_idx */ } /* !col_nm_in */ } /* !1D */ if(flg_grd_in_2D){ long lat_nbr_in_dat; /* [nbr] Number of latitudes in input datafile */ if(lat_nm_in && (rcd=nco_inq_dimid_flg(in_id,lat_nm_in,&dmn_id_lat)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"latitude",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("latitude"); else if((rcd=nco_inq_dimid_flg(in_id,"lat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("lat"); else if((rcd=nco_inq_dimid_flg(in_id,"Latitude",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Latitude"); else if((rcd=nco_inq_dimid_flg(in_id,"Lat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Lat"); else if((rcd=nco_inq_dimid_flg(in_id,"south_north",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("south_north"); /* WRF */ else if((rcd=nco_inq_dimid_flg(in_id,"south_north_stag",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("south_north_stag"); else if((rcd=nco_inq_dimid_flg(in_id,"YDim:location",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("YDim:location"); /* AIRS L3 */ else if((rcd=nco_inq_dimid_flg(in_id,"YDim:MOD_Grid_monthly_CMG_VI",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("YDim:MOD_Grid_monthly_CMG_VI"); /* MODIS MOD13C2 */ else if((rcd=nco_inq_dimid_flg(in_id,"natrack",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("natrack"); /* MODIS DeepBlue SeaWiFS L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"nj",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nj"); /* CICE RTM */ else if((rcd=nco_inq_dimid_flg(in_id,"lsmlat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("lsmlat"); /* CISM/CLM/ELM */ else if((rcd=nco_inq_dimid_flg(in_id,"nlat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nlat"); /* POP */ else if((rcd=nco_inq_dimid_flg(in_id,"rlat",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("rlat"); /* RACMO */ else if((rcd=nco_inq_dimid_flg(in_id,"nscan",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nscan"); /* AMSR, TRMM */ else if((rcd=nco_inq_dimid_flg(in_id,"nTimes",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("nTimes"); /* OMI L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"number_of_lines",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("number_of_lines"); /* DSCOVR L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoTrack",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("GeoTrack"); /* AIRS L2 DAP NC */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoTrack:L2_Standard_atmospheric&surface_product",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("GeoTrack:L2_Standard_atmospheric&surface_product"); /* AIRS L2 HDF */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Along_Swath:mod04",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Cell_Along_Swath:mod04"); /* MODIS MOD04 L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Along_Swath_mod04",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("Cell_Along_Swath_mod04"); /* MODIS MOD04 L2 (ncl_convert2nc changes colon to underscore) */ else if((rcd=nco_inq_dimid_flg(in_id,"CO_Latitude",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("CO_Latitude"); else if((rcd=nco_inq_dimid_flg(in_id,"j",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("j"); /* CMIP5 NorESM1 ocean */ else if((rcd=nco_inq_dimid_flg(in_id,"latitude0",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("latitude0"); /* Oxford */ else if((rcd=nco_inq_dimid_flg(in_id,"y",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("y"); /* NEMO */ else if((rcd=nco_inq_dimid_flg(in_id,"x",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("x"); /* NSIDC polar stereographic (NB: unfortunate incompatible conflict between NEMO & NSIDC names) */ else if((rcd=nco_inq_dimid_flg(in_id,"y1",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("y1"); /* NSIDC EASE */ else if((rcd=nco_inq_dimid_flg(in_id,"ygrid",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("ygrid"); /* SSM/I */ else if((rcd=nco_inq_dimid_flg(in_id,"ygrid_0",&dmn_id_lat)) == NC_NOERR) lat_nm_in=strdup("ygrid_0"); /* NWS HRRR */ else{ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports unable to find latitude dimension in input file. Tried the usual suspects. HINT: Inform regridder of input latitude dimension name with \"ncks --rgr lat_nm_in=name\" or \"ncremap -R '--rgr lat_nm_in=name'\"\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !lat */ rcd=nco_inq_dimlen(in_id,dmn_id_lat,&lat_nbr_in_dat); if(lat_nbr_in != lat_nbr_in_dat && !flg_grd_in_1D_dat_in_2D){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports mapfile and data file dimension sizes disagree: mapfile lat_nbr_in = %ld != %ld = lat_nbr_in from datafile. HINT: Check that source grid (i.e., \"grid A\") used to create mapfile matches grid on which data are stored in input datafile.\n",nco_prg_nm_get(),fnc_nm,lat_nbr_in,lat_nbr_in_dat); nco_exit(EXIT_FAILURE); } /* !err */ long lon_nbr_in_dat; /* [nbr] Number of longitudes in input datafile */ if(lon_nm_in && (rcd=nco_inq_dimid_flg(in_id,lon_nm_in,&dmn_id_lon)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"longitude",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("longitude"); else if((rcd=nco_inq_dimid_flg(in_id,"lon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("lon"); else if((rcd=nco_inq_dimid_flg(in_id,"Longitude",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Longitude"); else if((rcd=nco_inq_dimid_flg(in_id,"Lon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Lon"); else if((rcd=nco_inq_dimid_flg(in_id,"west_east",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("west_east"); /* WRF */ else if((rcd=nco_inq_dimid_flg(in_id,"west_east_stag",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("west_east_stag"); else if((rcd=nco_inq_dimid_flg(in_id,"XDim:location",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("XDim:location"); /* AIRS L3 */ else if((rcd=nco_inq_dimid_flg(in_id,"XDim:MOD_Grid_monthly_CMG_VI",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("XDim:MOD_Grid_monthly_CMG_VI"); /* MODIS MOD13C2 */ else if((rcd=nco_inq_dimid_flg(in_id,"ni",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("ni"); /* CICE RTM */ else if((rcd=nco_inq_dimid_flg(in_id,"lsmlon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("lsmlon"); /* CISM/CLM/ELM */ else if((rcd=nco_inq_dimid_flg(in_id,"nlon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("nlon"); /* POP */ else if((rcd=nco_inq_dimid_flg(in_id,"rlon",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("rlon"); /* POP */ else if((rcd=nco_inq_dimid_flg(in_id,"npix",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("npix"); /* AMSR */ else if((rcd=nco_inq_dimid_flg(in_id,"npixel",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("npixel"); /* TRMM */ else if((rcd=nco_inq_dimid_flg(in_id,"nxtrack",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("nxtrack"); /* MODIS DeepBlue SeaWiFS L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"nXtrack",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("nXtrack"); /* OMI L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"number_of_pixels",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("number_of_pixels"); /* DSCOVR L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoXTrack",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("GeoXTrack"); /* AIRS L2 DAP NC */ else if((rcd=nco_inq_dimid_flg(in_id,"GeoXTrack:L2_Standard_atmospheric&surface_product",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("GeoXTrack:L2_Standard_atmospheric&surface_product"); /* AIRS L2 HDF */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Across_Swath:mod04",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Cell_Across_Swath:mod04"); /* MODIS MOD04 L2 */ else if((rcd=nco_inq_dimid_flg(in_id,"Cell_Across_Swath_mod04",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("Cell_Across_Swath_mod04"); /* MODIS MOD04 L2 (ncl_convert2nc changes colon to underscore) */ else if((rcd=nco_inq_dimid_flg(in_id,"i",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("i"); /* CMIP5 NorESM1 ocean */ else if((rcd=nco_inq_dimid_flg(in_id,"longitude0",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("longitude0"); /* Oxford */ else if((rcd=nco_inq_dimid_flg(in_id,"x",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("x"); /* NEMO */ else if((rcd=nco_inq_dimid_flg(in_id,"y",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("y"); /* NSIDC polar stereographic (NB: unfortunate incompatible conflict between NEMO & NSIDC names) */ else if((rcd=nco_inq_dimid_flg(in_id,"x1",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("x1"); /* NSIDC EASE */ else if((rcd=nco_inq_dimid_flg(in_id,"xgrid",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("xgrid"); /* SSM/I */ else if((rcd=nco_inq_dimid_flg(in_id,"xgrid_0",&dmn_id_lon)) == NC_NOERR) lon_nm_in=strdup("xgrid_0"); /* NWS HRRR */ else{ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports unable to find longitude dimension in input file. Tried the usual suspects. HINT: Inform regridder of input longitude dimension name with \"ncks --rgr lon_nm_in=name\" or \"ncremap -R '--rgr lon_nm_in=name'\"\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !lat */ rcd=nco_inq_dimlen(in_id,dmn_id_lon,&lon_nbr_in_dat); if(lon_nbr_in != lon_nbr_in_dat && !flg_grd_in_1D_dat_in_2D){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") reports mapfile and data file dimension sizes disagree: mapfile lon_nbr_in = %ld != %ld = lon_nbr_in from datafile. HINT: Check that source grid (i.e., \"grid A\") used to create mapfile matches grid on which data are stored in input datafile.\n",nco_prg_nm_get(),fnc_nm,lon_nbr_in,lon_nbr_in_dat); nco_exit(EXIT_FAILURE); } /* !err */ if(flg_grd_in_1D_dat_in_2D){ if(lon_nbr_in_dat*lat_nbr_in_dat == col_nbr_in){ (void)fprintf(stdout,"%s: INFO %s Hail Mary algorithm reports tentative success in that product of identifed horizontal dimension sizes in the 2D input data file equals the map-file 1D dimension size = %ld.\n",nco_prg_nm_get(),fnc_nm,col_nbr_in); lat_nbr_in=lat_nbr_in_dat; lon_nbr_in=lon_nbr_in_dat; }else{ /* !col_nbr_in */ (void)fprintf(stdout,"%s: ERROR %s Hail Mary algorithm reports final failure since product of identifed horizontal dimension sizes in the 2D input data file does not equal the map-file 1D dimension size = %ld.\n",nco_prg_nm_get(),fnc_nm,col_nbr_in); nco_exit(EXIT_FAILURE); } /* !col_nbr_in */ } /* !flg_grd_in_1D_dat_in_2D */ } /* !2D */ /* Do not extract grid variables (that are also extensive variables) like lon, lat, area, and masks If necessary, use remap data to diagnose them from scratch Other extensive variables (like counts, population) will be extracted and summed not averaged */ /* Exception list source: ALM/CLM: landmask (20170504: Debatable, including erroneous mask may be better than completely excluding an expected mask) (20170504: must keep landfrac since regridded by ncremap for SGS option) AMSR: Latitude, Longitude CAM, CERES, CMIP5: lat, lon CAM, CMIP5: gw, lat_bnds, lon_bnds CAM-FV: slon, slat, w_stag (w_stag is weights for slat grid, analagous to gw for lat grid) CAM-SE, EAM, MOSART: area CICE: latt_bounds, lont_bounds, latu_bounds, lonu_bounds, TLAT, TLON, ULAT, ULON (NB: CICE uses ?LON and POP uses ?LONG) (aice is ice area, tmask is state-variable mask, both not currently excluded, although all binary masks like tmask should be recomputed on new grid) CISM/CLM/ELM: LATIXY, LONGXY (glacier mask files) DSCOVR L2: latitude, longitude ESMF: gridcell_area GPM: S1_Latitude, S1_Longitude HIRDLS: Latitude MAR/RACMO: LAT, LON MLS: CO_Latitude MPAS-O/I/LI: areaCell, latCell, lonCell and others that are all handled by separated MPAS convention implementation below NCO: lat_vertices, lon_vertices NEMO: nav_lat, nav_lon NWS HRRR: gridlat_0, gridlon_0 OCO2: latitude_bnds, longitude_bnds OMI DOMINO: Latitude, LatitudeCornerpoints, Longitude, LongitudeCornerpoints Oxford: global_latitude0, global_longitude0, latitude0, longitude0 POP: TLAT, TLONG, ULAT, ULONG (NB: CICE uses ?LON and POP uses ?LONG) (POP does not archive spatial bounds) RACMO: rlat, rlon TRMM: Latitude, Longitude UV-CDAT regridder: bounds_lat, bounds_lon Unknown: XLAT_M, XLONG_M WRF: XLAT, XLONG */ const int var_xcl_lst_nbr=53; /* [nbr] Number of objects on exclusion list */ const char *var_xcl_lst[]={"/area","/gridcell_area","/gw","/LAT","/lat","/Latitude","/latitude","/nav_lat","/global_latitude0","gridlat_0","/latitude0","/rlat","/slat","/LATIXY","/LONGXY","/TLAT","/ULAT","/XLAT","/XLAT_M","/CO_Latitude","/S1_Latitude","/lat_bnds","/lat_vertices","/latt_bounds","/latu_bounds","/latitude_bnds","/LatitudeCornerpoints","/bounds_lat","/LON","/lon","/Longitude","/longitude","/nav_lon","/global_longitude0","gridlon_0","/longitude0","/rlon","/slon","/TLON","/TLONG","/ULON","/ULONG","/XLONG","/XLONG_M","/CO_Longitude","/S1_Longitude","/lon_bnds","/lon_vertices","/lont_bounds","/lonu_bounds","/longitude_bnds","/LongitudeCornerpoints","/bounds_lon","/w_stag"}; int var_cpy_nbr=0; /* [nbr] Number of copied variables */ int var_rgr_nbr=0; /* [nbr] Number of regridded variables */ int var_xcl_nbr=0; /* [nbr] Number of deleted variables */ int var_crt_nbr=0; /* [nbr] Number of created variables */ int var_xtn_nbr=0; /* [nbr] Number of extensive variables */ unsigned int idx_tbl; /* [idx] Counter for traversal table */ const unsigned int trv_nbr=trv_tbl->nbr; /* [idx] Number of traversal table entries */ for(idx=0;idx<var_xcl_lst_nbr;idx++){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm_fll,var_xcl_lst[idx])) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* endif */ } /* !idx */ cnv_sct *cnv; /* [sct] Convention structure */ /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id); if(cnv->MPAS){ /* 20160228: MPAS has a host of mysterious grid and extensive variables that should probably not be regridded 20180206: Add from MPAS-LI xCell, yCell, zCell, and [xyz]Edge, and [xyz]Vertex 20180917: Restrict exclusion list to a subset of variables with nCells-dimension Six nCells-variables may be valuable when regridded to lat/lon mpas_xcl_lst in nco_rgr_wgt() and MPAS var_xcl_lst in nco_var_is_fix() differ by these six variables: areaCell for comparison to area(lat,lon) cellMask for area-weighted mask maxLevelCell for area-weighted underwater topographic mask xCell, yCell, zCell for area-weighted cartesian coordinates 20180918: Regridder currently only works on cell-based coordinates Decided regridder will omit not copy fields on vertex- or edge-based coordinates until it can regrid them Regridding vertex- or edge-based fields would require new sparse matrix for vertices or edges How would ERWG or TempestRemap handle that? MPAS geophysical variables on vertex-based (not cell-based) coordinates include: avg_airStressVertexUGeo_1, avg_airStressVertexVGeo_1, uOceanVelocityVertexGeo_1, uVelocityGeo_1, vOceanVelocityVertexGeo_1, vVelocityGeo_1 MPAS geophysical variables on edge-based (not cell-based) coordinates include: principalStress1Var_1, principalStress2Var_1 */ const int mpas_xcl_lst_nbr=35; const char *mpas_xcl_lst[]={"/angleEdge","/areaTriangle","/cellsOnCell","/cellsOnEdge","/cellsOnVertex","/dcEdge","/dvEdge","/edgeMask","/edgesOnCell","/edgesOnEdge","/edgesOnVertex","/indexToCellID","/indexToEdgeID","/indexToVertexID","/kiteAreasOnVertex","/latCell","/latEdge","/latVertex","/lonCell","/lonEdge","/lonVertex","/maxLevelEdgeTop","/meshDensity","/nEdgesOnCell","/nEdgesOnEdge","/vertexMask","/verticesOnCell","/verticesOnEdge","/weightsOnEdge","/xEdge","/yEdge","/zEdge","/xVertex","/yVertex","/zVertex"}; for(idx=0;idx<mpas_xcl_lst_nbr;idx++){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++) if(!strcmp(trv_tbl->lst[idx_tbl].nm_fll,mpas_xcl_lst[idx])) break; if(idx_tbl < trv_nbr){ if(trv_tbl->lst[idx_tbl].flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) pre-defined MPAS exclusion-list variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); var_xcl_nbr++; } /* endif */ trv_tbl->lst[idx_tbl].flg_xtr=False; } /* endif */ } /* !idx */ } /* !MPAS */ char *dmn_nm_cp; /* [sng] Dimension name as char * to reduce indirection */ int dmn_nbr_in; /* [nbr] Number of dimensions in input variable */ int dmn_nbr_out; /* [nbr] Number of dimensions in output variable */ nco_bool has_lon; /* [flg] Contains longitude dimension */ nco_bool has_lat; /* [flg] Contains latitude dimension */ trv_sct trv; /* [sct] Traversal table object structure to reduce indirection */ /* Define regridding flag for each variable */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; dmn_nbr_in=trv_tbl->lst[idx_tbl].nbr_dmn; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ has_lon=False; has_lat=False; if(flg_grd_in_2D){ for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ /* Pre-determine flags necessary during next loop */ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; /* fxm: Generalize to include any variable containing two coordinates with "standard_name" = "latitude" and "longitude" */ if(!has_lon) has_lon=!strcmp(dmn_nm_cp,lon_nm_in); if(!has_lat) has_lat=!strcmp(dmn_nm_cp,lat_nm_in); } /* end loop over dimensions */ } /* !flg_grd_in_2D */ for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; /* Regrid variables containing the horizontal spatial dimension on 1D grids, and both latitude and longitude on 2D grids */ if(!strcmp(dmn_nm_cp,col_nm_in) || (has_lon && has_lat)){ trv_tbl->lst[idx_tbl].flg_rgr=True; var_rgr_nbr++; break; } /* endif */ } /* end loop over dimensions */ if(dmn_idx == dmn_nbr_in){ /* Not regridded, so must be omitted or copied... */ if(flg_grd_in_2D && (has_lon || has_lat)){ /* Single spatial dimensional variables on 2D input grids are likely extensive (e.g., grd_mrd_lng from bds) These could be salvaged with explicit rules or implicit assumptions */ trv_tbl->lst[idx_tbl].flg_xtr=False; var_xcl_nbr++; if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO automatically omitting (not copying or regridding from input) extensive-seeming (e.g., 1D spatial variable in 2D input grid, or 2D spatial variable without primary grid dimensions from multi-grid file (e.g., west_east_stag or south_north_stag instead of west_east or south_north)) variable %s\n",nco_prg_nm_get(),trv_tbl->lst[idx_tbl].nm_fll); }else{ /* !omitted */ /* Copy all variables that are not regridded or omitted */ var_cpy_nbr++; } /* !omitted */ } /* endif not regridded */ } /* end nco_obj_typ_var */ } /* end idx_tbl */ if(!var_rgr_nbr) (void)fprintf(stdout,"%s: WARNING %s reports no variables fit regridding criteria. The regridder expects something to regrid, and variables not regridded are copied straight to output. HINT: If the name(s) of the input horizontal spatial dimensions to be regridded (e.g., latitude and longitude or column) do not match NCO's preset defaults (case-insensitive unambiguous forms and abbreviations of \"latitude\", \"longitude\", and \"ncol\", respectively) then change the dimension names that NCO looks for. Instructions are at http://nco.sf.net/nco.html#regrid, e.g., \"ncks --rgr col=lndgrid --rgr lat=north\" or \"ncremap -R '--rgr col=lndgrid --rgr lat=north'\".\n",nco_prg_nm_get(),fnc_nm); for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.flg_rgr){ for(int xtn_idx=0;xtn_idx<rgr->xtn_nbr;xtn_idx++){ /* 20150927: Extensive variable treatments are still in alpha-development Currently testing on AIRS TSurfStd_ct (by summing not averaging) In future may consider variables that need more complex (non-summing) extensive treatment MPAS-O/I has a zillion of these [xyz]Cell, cellsOnCell, fCell, indexToCellID, maxLevelCell, meshDensity Not to mention the variables that depend on nEdges and nVertices... */ if(!strcmp(trv.nm,rgr->xtn_var[xtn_idx])){ trv_tbl->lst[idx_tbl].flg_xtn=True; var_xtn_nbr++; if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"%s: INFO Variable %s will be treated as extensive (summed not averaged)\n",nco_prg_nm_get(),trv.nm_fll); } /* !strcmp */ } /* !xtn_idx */ } /* !flg_rgr */ } /* !idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_sbr){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr) (void)fprintf(stderr,"Regrid %s? %s\n",trv.nm,trv.flg_rgr ? "Yes" : "No"); } /* end idx_tbl */ } /* end dbg */ /* Lay-out regridded file */ aed_sct aed_mtd; char *area_nm_out; char *att_nm; char *bnd_nm_out; char *bnd_tm_nm_out; char *col_nm_out; char *frc_nm_out; char *lat_bnd_nm_out; char *lat_dmn_nm_out; char *lat_nm_out; char *lat_wgt_nm; char *lon_bnd_nm_out; char *lon_dmn_nm_out; char *lon_nm_out; char *msk_nm_out; char *slat_nm_out=NULL; char *slat_wgt_nm_out=NULL; char *slon_nm_out=NULL; int dmn_id_bnd; /* [id] Dimension ID */ int dmn_id_bnd_tm; /* [id] Dimension ID */ int dmn_id_slat; /* [id] Dimension ID */ int dmn_id_slon; /* [id] Dimension ID */ int area_out_id; /* [id] Variable ID for area */ int frc_out_id; /* [id] Variable ID for fraction */ int lon_out_id; /* [id] Variable ID for longitude */ int lat_out_id; /* [id] Variable ID for latitude */ int lat_wgt_id; /* [id] Variable ID for latitude weight */ int lon_bnd_id; /* [id] Variable ID for lon_bnds/lon_vertices */ int lat_bnd_id; /* [id] Variable ID for lat_bnds/lat_vertices */ int msk_out_id; /* [id] Variable ID for mask */ int slat_out_id; /* [id] Variable ID for staggered latitude */ int slat_wgt_id; /* [id] Variable ID for staggered latitude weight */ int slon_out_id; /* [id] Variable ID for staggered longitude */ int dmn_ids_out[dmn_nbr_grd_max]; /* [id] Dimension IDs array for output variable */ long dmn_srt_out[dmn_nbr_grd_max]; long dmn_cnt_tuo[dmn_nbr_grd_max]; /* Name output dimensions/variables */ area_nm_out=rgr->area_nm; bnd_tm_nm_out=rgr->bnd_tm_nm; frc_nm_out=rgr->frc_nm; lat_bnd_nm_out=rgr->lat_bnd_nm; lat_wgt_nm=rgr->lat_wgt_nm; lon_bnd_nm_out=rgr->lon_bnd_nm; msk_nm_out=rgr->msk_nm; /* Use explicitly specified output names, if any, otherwise use input names (either explicitly specified or discovered by fuzzing) */ if(rgr->col_nm_out) col_nm_out=rgr->col_nm_out; else col_nm_out=col_nm_in; if(rgr->lat_dmn_nm) lat_dmn_nm_out=rgr->lat_dmn_nm; else lat_dmn_nm_out=lat_nm_in; if(rgr->lon_dmn_nm) lon_dmn_nm_out=rgr->lon_dmn_nm; else lon_dmn_nm_out=lon_nm_in; if(rgr->lat_nm_out) lat_nm_out=rgr->lat_nm_out; else lat_nm_out=lat_nm_in; if(rgr->lon_nm_out) lon_nm_out=rgr->lon_nm_out; else lon_nm_out=lon_nm_in; if(flg_grd_out_1D){ bnd_nm_out=rgr->vrt_nm; lat_bnd_nm_out=rgr->lat_vrt_nm; lon_bnd_nm_out=rgr->lon_vrt_nm; } /* !flg_grd_out_1D */ if(flg_grd_out_crv){ bnd_nm_out=rgr->bnd_nm; } /* !flg_grd_out_crv */ if(flg_grd_out_rct){ bnd_nm_out=rgr->bnd_tm_nm; /* NB: default to bnd_tm_nm for spatial bounds */ } /* !flg_grd_out_rct */ if(flg_grd_out_2D){ lat_bnd_nm_out=rgr->lat_bnd_nm; lon_bnd_nm_out=rgr->lon_bnd_nm; } /* !flg_grd_out_2D */ if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ slat_nm_out=strdup("slat"); slat_wgt_nm_out=strdup("w_stag"); slon_nm_out=strdup("slon"); } /* !nco_grd_lat_fv */ /* Ensure temporal bounds dimension name is distinct from spatial bounds when their sizes differ */ if(bnd_nbr_out != bnd_tm_nbr_out){ if(!strcmp(bnd_nm_out,bnd_tm_nm_out)){ (void)fprintf(stdout,"%s: INFO %s reports spatial and temporal output bounds dimensions are identical (and named \"%s\") by default for rectangular output grids because both can be stored as 2D arrays. That cannot work for this mapping because temporal and spatial bounds dimensions sizes differ (bnd_nbr_out = %d, bnd_tm_nbr_out = %d). Using fall-back spatial bounds name \"%s\" instead. HINT: You may change one or both manually with \"ncks --rgr bnd_nm=name\" or \"ncks --rgr bnd_tm_nm=name\", or, using ncremap, with \"ncremap -R '--rgr bnd_nm=name'\" or \"ncremap -R '--rgr bnd_tm_nm=name'\"\n",nco_prg_nm_get(),fnc_nm,bnd_tm_nm_out,bnd_nbr_out,bnd_tm_nbr_out,bnd_nm_out); } /* !strcmp() */ } /* !bnd_nbr_out */ /* Persistent metadata */ aed_sct aed_mtd_crd; char *att_val_crd=NULL; char *att_nm_crd=NULL; att_nm_crd=strdup("coordinates"); aed_mtd_crd.att_nm=att_nm_crd; if(flg_grd_out_1D || flg_grd_out_crv) aed_mtd_crd.mode=aed_overwrite; else aed_mtd_crd.mode=aed_delete; aed_mtd_crd.type=NC_CHAR; aed_mtd_crd.sz=strlen(lat_nm_out)+strlen(lon_nm_out)+1L; att_val_crd=(char *)nco_malloc((aed_mtd_crd.sz+1L)*nco_typ_lng(aed_mtd_crd.type)); (void)sprintf(att_val_crd,"%s %s",lat_nm_out,lon_nm_out); aed_mtd_crd.val.cp=att_val_crd; /* Reminder: Regridder area_out options, e.g., --rgr area_out, set flg_area_out to control adding "area" variable to regridded output Regridder cll_msr options, --rgr cll_msr, set flg_cll_msr to control adding "cell_measures" attribute to regridded output ncks & ncra cll_msr options, --cll_msr, set EXTRACT_CLL_MSR to control adding "cell_measures" variables (e.g., area) to extraction list of input file EXTRACT_CLL_MSR supercedes --rgr area_out in determining whether to add "area" to regridded output */ nco_bool flg_area_out=rgr->flg_area_out; /* [flg] Add area to output */ nco_bool flg_cll_msr=rgr->flg_cll_msr; /* [flg] Add cell_measures attribute */ aed_sct aed_mtd_cll_msr; char *att_nm_cll_msr=NULL; char *att_val_cll_msr=NULL; if(flg_cll_msr){ att_nm_cll_msr=strdup("cell_measures"); aed_mtd_cll_msr.att_nm=att_nm_cll_msr; aed_mtd_cll_msr.mode=aed_overwrite; aed_mtd_cll_msr.type=NC_CHAR; att_val_cll_msr=(char *)nco_malloc((strlen(area_nm_out)+6L+1L)*nco_typ_lng(aed_mtd_cll_msr.type)); (void)sprintf(att_val_cll_msr,"area: %s",area_nm_out); aed_mtd_cll_msr.sz=strlen(att_val_cll_msr); aed_mtd_cll_msr.val.cp=att_val_cll_msr; } /* !flg_cll_msr */ /* Define new horizontal dimensions before all else */ if(flg_grd_out_1D){ rcd+=nco_def_dim(out_id,col_nm_out,col_nbr_out,&dmn_id_col); } /* !flg_grd_out_1D */ if(flg_grd_out_2D){ rcd+=nco_def_dim(out_id,lat_dmn_nm_out,lat_nbr_out,&dmn_id_lat); rcd+=nco_def_dim(out_id,lon_dmn_nm_out,lon_nbr_out,&dmn_id_lon); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ rcd+=nco_def_dim(out_id,slat_nm_out,slat_nbr_out,&dmn_id_slat); rcd+=nco_def_dim(out_id,slon_nm_out,slon_nbr_out,&dmn_id_slon); } /* !nco_grd_lat_fv */ } /* !flg_grd_out_2D */ /* If dimension has not been defined, define it */ rcd=nco_inq_dimid_flg(out_id,bnd_tm_nm_out,&dmn_id_bnd_tm); if(rcd != NC_NOERR) rcd=nco_def_dim(out_id,bnd_tm_nm_out,bnd_tm_nbr_out,&dmn_id_bnd_tm); /* If dimension has not been defined, define it */ rcd=nco_inq_dimid_flg(out_id,bnd_nm_out,&dmn_id_bnd); if(rcd != NC_NOERR) rcd=nco_def_dim(out_id,bnd_nm_out,bnd_nbr_out,&dmn_id_bnd); char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ char *var_nm; /* [sng] Variable name */ int *dmn_id_in=NULL; /* [id] Dimension IDs */ int *dmn_id_out=NULL; /* [id] Dimension IDs */ int var_id_in; /* [id] Variable ID */ int var_id_out; /* [id] Variable ID */ nc_type var_typ_out; /* [enm] Variable type to write to disk */ nc_type var_typ_rgr; /* [enm] Variable type used during regridding */ nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes "scale_factor", "add_offset" */ int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; dfl_lvl=rgr->dfl_lvl; fl_out_fmt=rgr->fl_out_fmt; /* Define new coordinates and grid variables in regridded file */ if(flg_grd_out_1D){ rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_col; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lat_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_col; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lon_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd+=nco_def_var(out_id,frc_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col,&frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,frc_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd+=nco_def_var(out_id,msk_nm_out,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_col,&msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_msk_out */ } /* !flg_grd_out_1D */ if(flg_grd_out_crv){ dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_lon; rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd+=nco_def_var(out_id,frc_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,frc_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd+=nco_def_var(out_id,msk_nm_out,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids_out,&msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_msk_out */ dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_lon; dmn_ids_out[2]=dmn_id_bnd; rcd+=nco_def_var(out_id,lat_bnd_nm_out,crd_typ_out,dmn_nbr_3D,dmn_ids_out,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_bnd_nm_out,crd_typ_out,dmn_nbr_3D,dmn_ids_out,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_grd_out_crv */ if(flg_grd_out_rct){ rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lat,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lon,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ rcd+=nco_def_var(out_id,slat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_slat,&slat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,slat_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,slat_wgt_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_slat,&slat_wgt_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,slat_wgt_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,slon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_slon,&slon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,slon_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !nco_grd_lat_fv */ dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lat_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_lon; dmn_ids_out[1]=dmn_id_bnd; rcd+=nco_def_var(out_id,lon_bnd_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; rcd+=nco_def_var(out_id,lat_wgt_nm,crd_typ_out,dmn_nbr_1D,&dmn_id_lat,&lat_wgt_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_wgt_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; dmn_ids_out[0]=dmn_id_lat; dmn_ids_out[1]=dmn_id_lon; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd+=nco_def_var(out_id,frc_nm_out,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,frc_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd+=nco_def_var(out_id,msk_nm_out,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids_out,&msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_out_id,shuffle,deflate,dfl_lvl); var_crt_nbr++; } /* !flg_msk_out */ } /* !flg_grd_out_rct */ /* Add _FillValue to empty destination cells, if requested */ nco_bool flg_add_fll=rgr->flg_add_fll; /* [flg] Add _FillValue to fields with empty destination cells */ nco_bool flg_dst_mpt=False; /* [flg] At least one destination cell is empty */ size_t dst_idx; /* [idx] Index on destination grid */ /* Determine whether any destination cells are, in fact, empty Logic here could be replaced by examining frac_b variable, if we trust input frac_b... ...and we do trust input frac_b since it is already used for renormalization */ if(flg_add_fll){ if(flg_msk_apl){ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(msk_out[dst_idx] == 0) break; if(dst_idx < grd_sz_out) flg_dst_mpt=True; if(flg_dst_mpt && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports at least one destination cell, Fortran (1-based) row index %lu, is empty. User requested (with --msk_apl) that masked cells receive _FillValue, so regridder will ensure that all regridded fields have _FillValue attribute.\n",nco_prg_nm_get(),fnc_nm,dst_idx+1L); }else{ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ /* For each destination cell... */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ /* ...does any weight... */ if(row_dst_adr[lnk_idx] == dst_idx){ /* ...contribute to that cell? */ /* If so, break lnk_idx loop and continue to next iteration of dst_idx loop */ break; } /* !row_dst_adr */ } /* !lnk_idx */ /* If weight loop reached end without a match, then this destination cell is empty */ if(lnk_idx == lnk_nbr){ flg_dst_mpt=True; break; } /* !lnk_idx */ } /* !dst_idx */ if(flg_dst_mpt && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports at least one destination cell, Fortran (1-based) row index %lu, is empty. User requested (with --add_fll) that empty cells receive _FillValue, so regridder will ensure that all regridded fields have _FillValue attribute.\n",nco_prg_nm_get(),fnc_nm,dst_idx+1L); } /* !flg_msk_apl */ } /* !flg_add_fll */ /* Pre-allocate dimension ID and cnt/srt space */ int dmn_nbr_max; /* [nbr] Maximum number of dimensions variable can have in input or output */ int dmn_in_fst; /* [idx] Offset of input- relative to output-dimension due to non-MRV dimension insertion/deletion */ int dmn_idx_col; /* [idx] Dimension position for column in this variable, used as flag */ int dmn_nbr_rec; /* [nbr] Number of unlimited dimensions */ int *dmn_ids_rec=NULL; /* [id] Unlimited dimension IDs */ rcd+=nco_inq_ndims(in_id,&dmn_nbr_max); dmn_nbr_max++; /* Safety in case regridding adds dimension */ dmn_id_in=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* Identify all record-dimensions in input file */ rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ int flg_pck; /* [flg] Variable is packed on disk */ nco_bool has_mss_val; /* [flg] Has numeric missing value attribute */ double mss_val_dbl; double mss_val_cmp_dbl; /* Missing value for comparison to double precision values */ /* Define regridded and copied variables in output file */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv_tbl->lst[idx_tbl].flg_mrv=True; trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ var_nm=trv.nm; /* Preserve input type in output type */ var_typ_out=trv.var_typ; /* Demote DP to SP to save space. fxm: missing value type will then be inconsistent if copied without demotion */ //if(trv.var_typ == NC_DOUBLE) var_typ_out=NC_FLOAT; else var_typ_out=trv.var_typ; dmn_nbr_in=trv.nbr_dmn; dmn_nbr_out=trv.nbr_dmn; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid_flg(out_id,var_nm,&var_id_out); /* If variable has not been defined, define it */ if(rcd != NC_NOERR){ if(trv.flg_rgr){ /* Regrid */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); dmn_in_fst=0; dmn_idx_col=NC_MIN_INT; rcd=nco_inq_var_packing(in_id,var_id_in,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports variable \"%s\" is packed so results unpredictable. HINT: If regridded values seems weird, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,var_nm); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); /* Is horizontal dimension last, i.e., most-rapidly-varying? */ if(flg_grd_in_1D && !strcmp(dmn_nm,col_nm_in)){ if(dmn_idx != dmn_nbr_in-1){ /* Unstructured input grid has col in non-MRV location (expect this with, e.g., MPAS-O/I native grid dimension-ordering */ (void)fprintf(stdout,"%s: WARNING %s reports unstructured grid spatial coordinate %s is (zero-based) dimension %d of input variable to be regridded %s which has %d dimensions. The NCO regridder does not support unstructured spatial dimensions that are not the last (i.e., most rapidly varying) dimension of an input variable, so results are likely garbage.\nHINT: Re-arrange input file dimensions to place horizontal dimension(s) last with, e.g., \'ncpdq -a time,lev,%s in.nc out.nc\' prior to calling the regridder. E3SM users: If this is an MPAS dataset with a new (unknown to ncremap) dimension, please ask Charlie to add the dimension to the ncremap dimension permutation list.\n",nco_prg_nm_get(),fnc_nm,dmn_nm,dmn_idx,var_nm,dmn_nbr_in,dmn_nm); trv_tbl->lst[idx_tbl].flg_mrv=False; } /* !dmn_idx */ } /* !flg_grd_in_1D */ if(flg_grd_in_2D && (!strcmp(dmn_nm,lat_nm_in) || !strcmp(dmn_nm,lon_nm_in))){ /* Are horizontal dimensions most-rapidly-varying? */ if(dmn_idx != dmn_nbr_in-1 && dmn_idx != dmn_nbr_in-2){ /* NB: Lat/lon input grid has lat/lon in non-MRV location (expect this with, e.g., AIRS L2 grid dimension-ordering */ (void)fprintf(stdout,"%s: WARNING %s reports lat-lon grid spatial coordinate %s is (zero-based) dimension %d of input variable to be regridded %s which has %d dimensions. The NCO regridder does not support rectangular lat-lon dimension(s) that are not the last two (i.e., most rapidly varying) dimensions of an input variable, so results are likely garbage.\nHINT: Re-arrange input file dimensions to place horizontal dimensions last with, e.g., \'ncpdq -a time,lev,lat,lon in.nc out.nc\' prior to calling the regridder.\n",nco_prg_nm_get(),fnc_nm,dmn_nm,dmn_idx,var_nm,dmn_nbr_in); trv_tbl->lst[idx_tbl].flg_mrv=False; } /* !dmn_idx */ } /* !flg_grd_in_2D */ if(flg_grd_out_1D){ if((nco_rgr_typ == nco_rgr_grd_2D_to_1D) && (!strcmp(dmn_nm,lat_nm_in) || !strcmp(dmn_nm,lon_nm_in))){ /* Replace first orthogonal horizontal dimension by unstructured horizontal dimension already defined */ if(dmn_idx_col == NC_MIN_INT){ /* Replace first horizontal dimension encountered with column dimension */ dmn_id_out[dmn_idx]=dmn_id_col; dmn_cnt[dmn_idx]=col_nbr_out; dmn_idx_col=dmn_idx; }else{ /* Second horizontal dimension encountered is MRV horizontal dimension Eliminate MRV horizontal dimension position for 1D horizontal output grid Shift non-MRV dimensions to left for output after deleting MRV horizontal dimension */ dmn_id_out[dmn_idx]=NC_MIN_INT; dmn_cnt[dmn_idx]=NC_MIN_INT; dmn_nbr_out--; /* Reduce output dimension position of all subsequent input dimensions by one */ if(!trv_tbl->lst[idx_tbl].flg_mrv) dmn_in_fst=-1; } /* !dmn_idx_col */ }else{ /* Dimension col_nm_in has already been defined as col_nm_out, replicate all other dimensions */ if(!strcmp(dmn_nm,col_nm_in)) rcd=nco_inq_dimid_flg(out_id,col_nm_out,dmn_id_out+dmn_idx); else rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx+dmn_in_fst); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt+dmn_idx+dmn_in_fst); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt[dmn_idx+dmn_in_fst]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt[dmn_idx+dmn_in_fst],dmn_id_out+dmn_idx+dmn_in_fst); } /* !rcd */ } /* !lat && !lon */ } /* !flg_grd_out_1D */ if(flg_grd_out_2D){ if(nco_rgr_typ == nco_rgr_grd_1D_to_2D && !strcmp(dmn_nm,col_nm_in)){ /* Replace unstructured horizontal dimension by orthogonal horizontal dimensions already defined */ dmn_id_out[dmn_idx]=dmn_id_lat; dmn_id_out[dmn_idx+1]=dmn_id_lon; dmn_cnt[dmn_idx]=lat_nbr_out; dmn_cnt[dmn_idx+1]=lon_nbr_out; dmn_nbr_out++; /* Increase output dimension position of all subsequent input dimensions by one */ if(!trv_tbl->lst[idx_tbl].flg_mrv) dmn_in_fst=1; }else{ /* Dimensions lat/lon_nm_in have already been defined as lat/lon_nm_out, replicate all other dimensions */ if(!strcmp(dmn_nm,lat_nm_in)) rcd=nco_inq_dimid_flg(out_id,lat_dmn_nm_out,dmn_id_out+dmn_idx); else if(!strcmp(dmn_nm,lon_nm_in)) rcd=nco_inq_dimid_flg(out_id,lon_dmn_nm_out,dmn_id_out+dmn_idx); else rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx+dmn_in_fst); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt+dmn_idx+dmn_in_fst); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt[dmn_idx+dmn_in_fst]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt[dmn_idx+dmn_in_fst],dmn_id_out+dmn_idx+dmn_in_fst); } /* !rcd */ } /* !col */ } /* !1D_to_2D */ } /* !dmn_idx */ }else{ /* !flg_rgr */ /* Replicate non-regridded variables */ rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_id_in[dmn_idx],dmn_nm); rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_id_out+dmn_idx); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_id_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt[dmn_idx],dmn_id_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ } /* !flg_rgr */ rcd=nco_def_var(out_id,var_nm,var_typ_out,dmn_nbr_out,dmn_id_out,&var_id_out); /* Duplicate netCDF4 settings when possible */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC){ /* Deflation */ if(dmn_nbr_out > 0){ int dfl_lvl_in; /* [enm] Deflate level [0..9] */ rcd=nco_inq_var_deflate(in_id,var_id_in,&shuffle,&deflate,&dfl_lvl_in); /* Before netCDF 4.8.0, nco_def_var_deflate() could be called multiple times Properties of final invocation before nc_enddef() would take effect After netCDF 4.8.0 first instance of nco_def_var_deflate() takes effect */ if((deflate || shuffle) && dfl_lvl < 0){ /* Copy original filters if user did not explicity set dfl_lvl for output */ (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl_in); }else if(dfl_lvl >= 0){ /* Overwrite HDF Lempel-Ziv compression level, if requested */ deflate=(int)True; /* Turn-off shuffle when uncompressing otherwise chunking requests may fail */ if(dfl_lvl <= 0) shuffle=NC_NOSHUFFLE; /* Shuffle never, to my knowledge, increases filesize, so shuffle by default when manually deflating (and do not shuffle when uncompressing) */ if(dfl_lvl > 0) shuffle=NC_SHUFFLE; (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl); } /* !dfl_lvl */ } /* !dmn_nbr_out */ } /* !NC_FORMAT_NETCDF4 */ (void)nco_att_cpy(in_id,out_id,var_id_in,var_id_out,PCK_ATT_CPY); if(trv.flg_rgr){ aed_mtd_crd.var_nm=var_nm; aed_mtd_crd.id=var_id_out; (void)nco_aed_prc(out_id,var_id_out,aed_mtd_crd); if(flg_cll_msr){ aed_mtd_cll_msr.var_nm=var_nm; aed_mtd_cll_msr.id=var_id_out; (void)nco_aed_prc(out_id,var_id_out,aed_mtd_cll_msr); } /* !flg_cll_msr */ /* 20210602: Ensure all regridded variables have _FillValue if user requested _FillValue in empty cells and there are empty cells */ if(flg_add_fll && flg_dst_mpt){ /* Check for _FillValue here iff user requests non-default behavior */ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,(double *)NULL); if(!has_mss_val){ val_unn mss_val_dfl; /* [] Default _FillValue */ mss_val_dfl=nco_mss_val_dfl_get(var_typ_out); rcd=nco_put_att(out_id,var_id_out,"_FillValue",var_typ_out,1L,(void *)(&mss_val_dfl)); } /* !has_mss_val */ } /* !flg_add_fll */ } /* !flg_rgr */ } /* !rcd */ } /* !var */ } /* !idx_tbl */ /* Free pre-allocated array space */ /* col_nm_in will not otherwise be free'd if it was guessed as usual suspect */ if(col_nm_in != rgr->col_nm_in) col_nm_in=(char *)nco_free(col_nm_in); if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt) dmn_cnt=(long *)nco_free(dmn_cnt); if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); /* Define new metadata in regridded file */ if(flg_area_out){ rcd=nco_char_att_put(out_id,area_nm_out,"long_name","Solid angle subtended by gridcell"); rcd=nco_char_att_put(out_id,area_nm_out,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm_out,"units","steradian"); if(flg_grd_out_1D || flg_grd_out_crv) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); att_val=(char *)nco_calloc((strlen(lat_dmn_nm_out)+strlen(lon_dmn_nm_out)+8L),sizeof(char)); (void)sprintf(att_val,"%s, %s: sum",lat_dmn_nm_out,lon_dmn_nm_out); rcd=nco_char_att_put(out_id,area_nm_out,"cell_mathods",att_val); if(att_val) att_val=(char *)nco_free(att_val); } /* !flg_area_out */ if(flg_frc_out_wrt){ rcd=nco_char_att_put(out_id,frc_nm_out,"long_name","Fraction of gridcell valid on destination grid"); if(flg_grd_out_1D || flg_grd_out_crv) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); att_val=(char *)nco_calloc((strlen(lat_dmn_nm_out)+strlen(lon_dmn_nm_out)+8L),sizeof(char)); (void)sprintf(att_val,"%s, %s: sum",lat_dmn_nm_out,lon_dmn_nm_out); rcd=nco_char_att_put(out_id,frc_nm_out,"cell_mathods",att_val); } /* !flg_frc_out_wrt */ if(flg_msk_out){ rcd=nco_char_att_put(out_id,msk_nm_out,"long_name","Mask (0 = invalid destination, 1 = valid destination)"); if(flg_grd_out_1D || flg_grd_out_crv) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); } /* !flg_msk_out */ rcd=nco_char_att_put(out_id,lat_nm_out,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lat_nm_out,"standard_name","latitude"); rcd=nco_char_att_put(out_id,lat_nm_out,"units","degrees_north"); // 20200205: Attach "axis" attribute to single-dimensional geospatial coordinates not to two-dimensional coordinate variables per CF Conventions section 5.2 if(!flg_grd_out_crv) rcd=nco_char_att_put(out_id,lat_nm_out,"axis","Y"); double vld_min; vld_min=-90.0; att_nm=strdup("valid_min"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lat_nm_out; aed_mtd.id=lat_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_min; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lat_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); double vld_max; vld_max=90.0; att_nm=strdup("valid_max"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lat_nm_out; aed_mtd.id=lat_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_max; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lat_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,lat_nm_out,"bounds",lat_bnd_nm_out); if(flg_grd_out_rct) att_val=strdup("Gridcell latitude interfaces"); else att_val=strdup("Gridcell latitude vertices"); rcd=nco_char_att_put(out_id,lat_bnd_nm_out,"long_name",att_val); rcd=nco_char_att_put(out_id,lon_nm_out,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lon_nm_out,"standard_name","longitude"); rcd=nco_char_att_put(out_id,lon_nm_out,"units","degrees_east"); // 20200205: Attach "axis" attribute to single-dimensional geospatial coordinates not to two-dimensional coordinate variables per CF Conventions section 5.2 if(!flg_grd_out_crv) rcd=nco_char_att_put(out_id,lon_nm_out,"axis","X"); /* UGRID Conventions define "topology" and "modulo" attributes https://github.com/ugrid-conventions/ugrid-conventions My understanding is these should only be utilized for global grids */ if(nco_rgr_typ == nco_rgr_grd_2D_to_2D){ /* fxm: change this to check whether lon_spn >= 360 or nco_grd_xtn == global */ att_nm=strdup("modulo"); double modulo=360.0; aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&modulo; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,lon_nm_out,"topology","circular"); } /* !nco_rgr_grd_2D_to_2D */ if(lon_ctr_out[0] >= 0.0) vld_min=0.0; else vld_min=-180.0; att_nm=strdup("valid_min"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_min; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); if(lon_ctr_out[0] >= 0.0) vld_max=360.0; else vld_max=180.0; att_nm=strdup("valid_max"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=1; aed_mtd.type=NC_DOUBLE; aed_mtd.val.dp=&vld_max; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,lon_nm_out,"bounds",lon_bnd_nm_out); att_nm=strdup("bounds"); att_val=lon_bnd_nm_out; aed_mtd.att_nm=att_nm; aed_mtd.var_nm=lon_nm_out; aed_mtd.id=lon_out_id; aed_mtd.sz=strlen(att_val); aed_mtd.type=NC_CHAR; aed_mtd.val.cp=att_val; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,lon_out_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); if(flg_grd_out_rct) att_val=strdup("Gridcell longitude interfaces"); else att_val=strdup("Gridcell longitude vertices"); rcd=nco_char_att_put(out_id,lon_bnd_nm_out,"long_name",att_val); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ rcd=nco_char_att_put(out_id,slat_nm_out,"long_name","Latitude for staggered FV grid"); rcd=nco_char_att_put(out_id,slat_nm_out,"units","degrees_north"); rcd=nco_char_att_put(out_id,slat_wgt_nm_out,"long_name","Latitude weights for staggered FV grid"); rcd=nco_char_att_put(out_id,slon_nm_out,"long_name","Longitude for staggered FV grid"); rcd=nco_char_att_put(out_id,slon_nm_out,"units","degrees_east"); } /* !nco_grd_lat_fv */ if(flg_grd_out_rct) rcd=nco_char_att_put(out_id,lat_wgt_nm,"long_name","Latitude quadrature weights (normalized to sum to 2.0 on global grids)"); rcd=nco_char_att_put(out_id,NULL,"map_file",fl_in); rcd=nco_char_att_put(out_id,NULL,"input_file",rgr->fl_in); /* Annotate persistent metadata that should appear last in attribute list */ if(flg_grd_out_1D){ if(flg_area_out) rcd=nco_char_att_put(out_id,area_nm_out,att_nm_crd,att_val_crd); if(flg_frc_out_wrt) rcd=nco_char_att_put(out_id,frc_nm_out,att_nm_crd,att_val_crd); if(flg_msk_out) rcd=nco_char_att_put(out_id,msk_nm_out,att_nm_crd,att_val_crd); } /* !flg_grd_out_1D */ /* Persistent metadata */ if(att_nm_crd) att_nm_crd=(char *)nco_free(att_nm_crd); if(att_val_crd) att_val_crd=(char *)nco_free(att_val_crd); if(flg_cll_msr){ if(att_nm_cll_msr) att_nm_cll_msr=(char *)nco_free(att_nm_cll_msr); if(att_val_cll_msr) att_val_cll_msr=(char *)nco_free(att_val_cll_msr); } /* !flg_cll_msr */ if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ if(slat_nm_out) slat_nm_out=(char *)nco_free(slat_nm_out); if(slat_wgt_nm_out) slat_wgt_nm_out=(char *)nco_free(slat_wgt_nm_out); if(slon_nm_out) slon_nm_out=(char *)nco_free(slon_nm_out); } /* !nco_grd_lat_fv */ /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Begin data mode */ (void)nco_enddef(out_id); /* Write new coordinates and variables to regridded file */ if(flg_grd_out_1D){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,lat_out_id,dmn_srt_out,dmn_cnt_tuo,lat_ctr_out,crd_typ_out); dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,lon_out_id,dmn_srt_out,dmn_cnt_tuo,lon_ctr_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=col_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt_out,dmn_cnt_tuo,lat_bnd_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=col_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt_out,dmn_cnt_tuo,lon_bnd_out,crd_typ_out); if(flg_area_out){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,area_out_id,dmn_srt_out,dmn_cnt_tuo,area_out,crd_typ_out); } /* !flg_area_out */ if(flg_msk_out){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=col_nbr_out; (void)nco_put_vara(out_id,msk_out_id,dmn_srt_out,dmn_cnt_tuo,msk_out,(nc_type)NC_INT); } /* !flg_msk_out */ } /* !flg_grd_out_1D */ if(flg_grd_out_crv){ dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=lon_nbr_out; (void)nco_put_vara(out_id,lat_out_id,dmn_srt_out,dmn_cnt_tuo,lat_ctr_out,crd_typ_out); (void)nco_put_vara(out_id,lon_out_id,dmn_srt_out,dmn_cnt_tuo,lon_ctr_out,crd_typ_out); if(flg_area_out){ (void)nco_put_vara(out_id,area_out_id,dmn_srt_out,dmn_cnt_tuo,area_out,crd_typ_out); } /* !flg_area_out */ if(flg_frc_out_wrt){ (void)nco_put_vara(out_id,frc_out_id,dmn_srt_out,dmn_cnt_tuo,frc_out,crd_typ_out); } /* !flg_frc_out_wrt */ if(flg_msk_out){ (void)nco_put_vara(out_id,msk_out_id,dmn_srt_out,dmn_cnt_tuo,msk_out,(nc_type)NC_INT); } /* !flg_msk_out */ dmn_srt_out[0]=dmn_srt_out[1]=dmn_srt_out[2]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=lon_nbr_out; dmn_cnt_tuo[2]=bnd_nbr_out; /* NB: 20160803 Semantically confusing---curvilinear grids must write *_crn_out data into *_bnd_out arrays */ (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt_out,dmn_cnt_tuo,lat_crn_out,crd_typ_out); (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt_out,dmn_cnt_tuo,lon_crn_out,crd_typ_out); } /* !flg_grd_out_crv */ if(flg_grd_out_rct){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=lat_nbr_out; (void)nco_put_vara(out_id,lat_out_id,dmn_srt_out,dmn_cnt_tuo,lat_ctr_out,crd_typ_out); dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=lon_nbr_out; (void)nco_put_vara(out_id,lon_out_id,dmn_srt_out,dmn_cnt_tuo,lon_ctr_out,crd_typ_out); if(nco_grd_lat_typ == nco_grd_lat_fv && flg_stg){ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=slat_nbr_out; (void)nco_put_vara(out_id,slat_out_id,dmn_srt_out,dmn_cnt_tuo,slat_ctr_out,crd_typ_out); (void)nco_put_vara(out_id,slat_wgt_id,dmn_srt_out,dmn_cnt_tuo,slat_wgt_out,crd_typ_out); dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=slon_nbr_out; (void)nco_put_vara(out_id,slon_out_id,dmn_srt_out,dmn_cnt_tuo,slon_ctr_out,crd_typ_out); if(slat_ctr_out) slat_ctr_out=(double *)nco_free(slat_ctr_out); if(slat_wgt_out) slat_wgt_out=(double *)nco_free(slat_wgt_out); if(slon_ctr_out) slon_ctr_out=(double *)nco_free(slon_ctr_out); } /* !nco_grd_lat_fv */ dmn_srt_out[0]=0L; dmn_cnt_tuo[0]=lat_nbr_out; (void)nco_put_vara(out_id,lat_wgt_id,dmn_srt_out,dmn_cnt_tuo,lat_wgt_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt_out,dmn_cnt_tuo,lat_bnd_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lon_nbr_out; dmn_cnt_tuo[1]=bnd_nbr_out; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt_out,dmn_cnt_tuo,lon_bnd_out,crd_typ_out); dmn_srt_out[0]=dmn_srt_out[1]=0L; dmn_cnt_tuo[0]=lat_nbr_out; dmn_cnt_tuo[1]=lon_nbr_out; if(flg_area_out){ (void)nco_put_vara(out_id,area_out_id,dmn_srt_out,dmn_cnt_tuo,area_out,crd_typ_out); } /* !flg_area_out */ if(flg_frc_out_wrt){ (void)nco_put_vara(out_id,frc_out_id,dmn_srt_out,dmn_cnt_tuo,frc_out,crd_typ_out); } /* !flg_frc_out_wrt */ if(flg_msk_out){ (void)nco_put_vara(out_id,msk_out_id,dmn_srt_out,dmn_cnt_tuo,msk_out,(nc_type)NC_INT); } /* !flg_msk_out */ } /* !flg_grd_out_rct */ /* Regrid or copy variable values */ const double wgt_vld_thr=rgr->wgt_vld_thr; /* [frc] Weight threshold for valid destination value */ const nco_bool flg_rnr=rgr->flg_rnr; /* [flg] Renormalize destination values by valid area */ char *sgs_frc_nm=NULL; char *sgs_msk_nm=NULL; double *sgs_frc_in=NULL; double *sgs_frc_out=NULL; double *var_val_dbl_in=NULL; double *var_val_dbl_out=NULL; double *wgt_vld_out=NULL; double var_val_crr; int *tally=NULL; /* [nbr] Number of valid (non-missing) values */ int lvl_idx; /* [idx] Level index */ int lvl_nbr; /* [nbr] Number of levels */ int thr_idx; /* [idx] Thread index */ size_t idx_in; /* [idx] Input grid index */ size_t idx_out; /* [idx] Output grid index */ size_t var_sz_in; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t var_sz_out; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t val_in_fst; /* [nbr] Number of elements by which current N-D slab input values are offset from origin */ size_t val_out_fst; /* [nbr] Number of elements by which current N-D slab output values are offset from origin */ /* 20190322: Prior to entering OpenMP loop, collect specified SGS information */ const double sgs_nrm=rgr->sgs_nrm; /* [frc] Sub-gridscale normalization */ if(rgr->sgs_frc_nm){ /* Normalization test: fl_in=20181217.CNTL_CNPCTC1850_OIBGC.ne30_oECv3.edison.clm2.h0.2000-12.nc /bin/cp -f ${DATA}/hdf/${fl_in} ~/elm_raw.nc ncremap -P sgs -v FSDS,TBOT,GPP -a aave -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/cmip6_180x360_scrip.20181001.nc ~/elm_raw.nc ~/elm_sgs.nc # Original SGS method ncks -A -v grid_area ${DATA}/grids/ne30np4_pentagons.091226.nc ~/elm_sgs.nc ncremap -P gsg -v FSDS,TBOT,GPP -m ${DATA}/maps/map_ne30np4_to_cmip6_180x360_aave.20181001.nc ~/elm_raw.nc ~/elm_gsg.nc # New SGS method */ if(rgr->sgs_msk_nm) sgs_msk_nm=(char *)strdup(rgr->sgs_msk_nm); sgs_frc_nm=(char *)strdup(rgr->sgs_frc_nm); var_nm=sgs_frc_nm; var_typ_rgr=NC_DOUBLE; /* NB: Regrid in double precision */ var_typ_out=NC_DOUBLE; /* NB: sgs_frc_out must be double precision */ var_sz_in=1L; /* Compute from scratch to be sure it matches grd_sz_in */ var_sz_out=grd_sz_out; /* Assume this holds */ char *fl_sgs=NULL; /* [sng] External sub-gridscale file name */ int sgs_id; /* [id] netCDF file ID for external sub-gridscale file */ sgs_id=in_id; if((rcd=nco_inq_varid_flg(sgs_id,var_nm,&var_id_in)) != NC_NOERR){ /* If sgs_frc_nm is not in input file then search for it in external area file */ #ifdef WIN32 const char sls_chr='\\'; /* [chr] Slash character */ #else /* !WIN32 */ const char sls_chr='/'; /* [chr] Slash character */ #endif /* !WIN32 */ char *sls_ptr; /* [sng] Pointer to last slash character (' ') */ sls_ptr=strrchr(var_nm,sls_chr); if(!sls_ptr){ (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unable to find sgs_frc_nm = %s in current input file, and unable to identify filename (ending with slash '/' or backslash '\\', as appropriate) portion of that string to serve as local external file for sgs_frc input, exiting\n",nco_prg_nm_get(),fnc_nm,sgs_frc_nm); nco_exit(EXIT_FAILURE); } /* !sls_ptr */ sgs_frc_nm=(char *)strdup(sls_ptr+1L); /* Copy variable-name portion of string */ *sls_ptr='\0'; /* NULL-terminate filename */ fl_sgs=(char *)strdup(var_nm); var_nm=sgs_frc_nm; /* NB: too tricky? */ rcd=nco_open(fl_sgs,NC_NOWRITE,&sgs_id); if((rcd=nco_inq_varid_flg(sgs_id,var_nm,&var_id_in)) != NC_NOERR){ (void)fprintf(stderr,"%s: ERROR %s (aka \"the regridder\") reports unable to find sgs_frc_nm = \"%s\" in local external file %s, exiting\n",nco_prg_nm_get(),fnc_nm,sgs_frc_nm,fl_sgs); nco_exit(EXIT_FAILURE); } /* !rcd */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s obtaining sgs_frc = %s from file %s\n",nco_prg_nm_get(),fnc_nm,sgs_frc_nm,fl_sgs); } /* !rcd */ rcd=nco_inq_varndims(sgs_id,var_id_in,&dmn_nbr_in); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_id_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(sgs_id,var_id_in,dmn_id_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(sgs_id,dmn_id_in[dmn_idx],dmn_cnt_in+dmn_idx); var_sz_in*=dmn_cnt_in[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ if(var_sz_in != grd_sz_in){ (void)fprintf(stdout,"%s: ERROR %s (aka \"the regridder\") requires that sgs_frc = %s be same size as spatial grid but var_sz_in = %lu != %lu = grd_sz_in\n",nco_prg_nm_get(),fnc_nm,var_nm,var_sz_in,grd_sz_in); nco_exit(EXIT_FAILURE); } /* !var_sz_in */ /* Missing value setup (NB: ELM landfrac has _FillValue and is _FillValue where masked */ has_mss_val=nco_mss_val_get_dbl(sgs_id,var_id_in,&mss_val_dbl); if(has_mss_val) mss_val_cmp_dbl=mss_val_dbl; else mss_val_cmp_dbl=NC_FILL_DOUBLE; sgs_frc_in=(double *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() sgs_frc_in value buffer"); rcd=nco_get_vara(sgs_id,var_id_in,dmn_srt,dmn_cnt_in,sgs_frc_in,var_typ_rgr); /* If sgs_frc comes from external local file, close it now */ if(fl_sgs){ rcd=nco_close(sgs_id); fl_sgs=(char *)nco_free(fl_sgs); } /* !fl_sgs */ /* Initialize output */ sgs_frc_out=(double *)nco_malloc_dbg(grd_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() sgs_frc_out value buffer"); /* Initialize and regrid sgs_frc_out 20190907: sgs_frc_in (landfrac) is _FillValue (1.0e36) for ELM datasets in all masked gridcells, and is always positive definite (never zero) in all unmasked gridcells because it it a true area. ELM sgs_frc_out is always positive definite gridcell area everywhere, with no missing values and no zero values. 20190910: MPAS-Seaice datasets have no mask, and sgs_frc_in (timeMonthly_avg_iceAreaCell) is never (ncatted-appended) _FillValue (-9.99999979021477e+33) and is usually zero because it is time-mean area-fraction of sea ice which only exists in polar regions. MPAS-Seaice sgs_frc_out is zero in all gridcells without sea-ice. Regardless of input source, following blocks guarantee that sgs_frc_out is defined everywhere, is never a missing value (sgs_frc_out is zero where sgs_frc_in may have been _FillValue), and is always safe to multiply and normalize by sgs_frc_out in main regridding loop */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) sgs_frc_out[dst_idx]=0.0; for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) if((var_val_crr=sgs_frc_in[col_src_adr[lnk_idx]]) != mss_val_cmp_dbl) sgs_frc_out[row_dst_adr[lnk_idx]]+=var_val_crr*wgt_raw[lnk_idx]; /* Sanity check sgs_frc_out */ if(nco_dbg_lvl_get() >= nco_dbg_fl){ /* 20190326: sgs_frc expressed as a fraction must never exceed sgs_nrm CICE expresses sgs_frc (aice) in percent, i.e., sgs_nrm=100.0 Sum total value of sgs_frc (as opposed to gridcell_area) depends on grid resolution */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ /* 20190907: Approximate comparison because rounding causes frequent exceedances of sgs_nrm by epsilon ~ 1.0e-15 */ if((float)sgs_frc_out[dst_idx] > sgs_nrm) (void)fprintf(stdout,"%s: INFO %s reports sgs_frc_out[%lu] = %19.15f > %g = sgs_nrm\n",nco_prg_nm_get(),fnc_nm,dst_idx,sgs_frc_out[dst_idx],sgs_nrm); } /* !dst_idx */ } /* !dbg */ // for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ // (void)fprintf(stdout,"%s: INFO %s reports sgs_frc_out[%lu] = %19.15f\n",nco_prg_nm_get(),fnc_nm,dst_idx,sgs_frc_out[dst_idx]); // } /* !dst_idx */ if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); } /* !sgs_frc_nm */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"Regridding progress: # means regridded, ~ means copied\n"); /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped as shared in parallel clause */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ /* OpenMP notes: default(none): GCC9.x does not accept this (https://github.com/nco/nco/issues/114) perhaps because of fp_stdout/stderr? Intel accepts it. firstprivate(): Pointers that could be inadvertently free()'d if they lost their NULL-initialization private(): Almost everything else shared(): uggh...shared clause depends on both compiler and compiler-version 1. Const variables (e.g., flg_rnr,fnc_nm,wgt_vld_thr) are default shared for gcc >= 4.9.2, 2. fnc_nm (only!) must be explicit shared for g++ 4.6.3 (travis) 3. flg_rnr,fnc_nm,wgt_vld_thr must be explicit shared for icc 13.1.3 (rhea) 4. assert() cannot be used in OpenMP blocks 5. Good discussion of "const" variables in shared() clause here http://jakascorner.com/blog/2016/07/omp-default-none-and-const.html 20200221: fxm Revisit default(none) in light of above article */ #ifdef __GNUG__ # define GCC_LIB_VERSION ( __GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__ ) # if GCC_LIB_VERSION < 490 # define GXX_OLD_OPENMP_SHARED_TREATMENT 1 # endif /* 480 */ # if GCC_LIB_VERSION >= 900 # define GXX_WITH_OPENMP5_GPU_SUPPORT 1 # endif /* 900 */ #endif /* !__GNUC__ */ #if defined( __INTEL_COMPILER) # pragma omp parallel for default(none) firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_cmp_dbl,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_add_fll,flg_frc_nrm,flg_msk_apl,flg_msk_out,flg_rnr,fnc_nm,frc_out,lnk_nbr,msk_out,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw,wgt_vld_thr) #else /* !__INTEL_COMPILER */ # ifdef GXX_OLD_OPENMP_SHARED_TREATMENT # pragma omp parallel for default(none) firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_cmp_dbl,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_add_fll,flg_frc_nrm,flg_msk_apl,flg_msk_out,flg_rnr,fnc_nm,frc_out,lnk_nbr,msk_out,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw) # else /* !old g++ */ # if defined(GXX_WITH_OPENMP5_GPU_SUPPORT) && 0 # pragma omp target teams distribute parallel for firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_cmp_dbl,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_add_fll,flg_frc_nrm,flg_msk_apl,flg_msk_out,flg_rnr,frc_out,lnk_nbr,msk_out,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw) # else # pragma omp parallel for firstprivate(dmn_cnt_in,dmn_cnt_out,dmn_srt,dmn_id_in,dmn_id_out,tally,var_val_dbl_in,var_val_dbl_out,wgt_vld_out) private(dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dst_idx,has_mss_val,idx,idx_in,idx_out,idx_tbl,in_id,lnk_idx,lvl_idx,lvl_nbr,mss_val_cmp_dbl,mss_val_dbl,rcd,thr_idx,trv,val_in_fst,val_out_fst,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr,var_val_crr) shared(col_src_adr,dmn_nbr_hrz_crd,flg_add_fll,flg_frc_nrm,flg_msk_apl,flg_msk_out,frc_out,lnk_nbr,msk_out,out_id,row_dst_adr,sgs_frc_nm,sgs_frc_in,sgs_frc_out,sgs_msk_nm,wgt_raw) # endif /* !GCC >= 9.0 */ # endif /* !GCC < 4.9 */ #endif /* !__INTEL_COMPILER */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; thr_idx=omp_get_thread_num(); in_id=trv_tbl->in_id_arr[thr_idx]; #ifdef _OPENMP if(nco_dbg_lvl_get() >= nco_dbg_grp && !thr_idx && !idx_tbl) (void)fprintf(fp_stdout,"%s: INFO %s reports regrid loop uses %d thread%s\n",nco_prg_nm_get(),fnc_nm,omp_get_num_threads(),(omp_get_num_threads() > 1) ? "s" : ""); if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO thread = %d, idx_tbl = %d, nm = %s\n",nco_prg_nm_get(),thr_idx,idx_tbl,trv.nm); #endif /* !_OPENMP */ if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s%s ",trv.flg_rgr ? "#" : "~",trv.nm); if(trv.flg_rgr){ /* Regrid variable */ var_nm=trv.nm; var_typ_rgr=NC_DOUBLE; /* NB: Perform regridding in double precision */ var_typ_out=trv.var_typ; /* NB: Output type in file is same as input type */ var_sz_in=1L; var_sz_out=1L; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid(out_id,var_nm,&var_id_out); rcd=nco_inq_varndims(in_id,var_id_in,&dmn_nbr_in); rcd=nco_inq_varndims(out_id,var_id_out,&dmn_nbr_out); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_id_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_id_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_id_in); rcd=nco_inq_vardimid(out_id,var_id_out,dmn_id_out); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_id_in[dmn_idx],dmn_cnt_in+dmn_idx); var_sz_in*=dmn_cnt_in[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ rcd=nco_inq_dimlen(out_id,dmn_id_out[dmn_idx],dmn_cnt_out+dmn_idx); if(dmn_cnt_out[dmn_idx] == 0L){ /* No records have been written, so overwrite zero output record size with input record size */ char dmn_rec_nm[NC_MAX_NAME]; /* [sng] Record dimension name */ int dmn_rec_id_in; rcd=nco_inq_dimname(out_id,dmn_id_out[dmn_idx],dmn_rec_nm); rcd=nco_inq_dimid(in_id,dmn_rec_nm,&dmn_rec_id_in); rcd=nco_inq_dimlen(in_id,dmn_rec_id_in,dmn_cnt_out+dmn_idx); } /* !dmn_cnt_out */ var_sz_out*=dmn_cnt_out[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ /* Compute number and size of non-lat/lon or non-col dimensions (e.g., level, time, species, wavelength) Denote their convolution by level or 'lvl' for shorthand There are lvl_nbr elements for each lat/lon or col position 20151011: Until today assume lat/lon and col are most-rapidly varying dimensions 20151011: Until today lvl_nbr missed last non-spatial dimension for 1D output */ lvl_nbr=1; /* Simple prescription of lvl_nbr works when horizontal dimension(s) is/are MRV */ for(dmn_idx=0;dmn_idx<dmn_nbr_out-dmn_nbr_hrz_crd;dmn_idx++) lvl_nbr*=dmn_cnt_out[dmn_idx]; /* Determining whether an individual field _uses_ missing values is important because memory requirements of next four malloc's (i.e., exclusive of wgt_raw) can sum to ~7*sizeof(uncompressed var) for NC_FLOAT and ~3.5*sizeof(uncompressed var) for NC_DOUBLE. Traditionally has_mss_val answers "does this variable _have_ and explicit missing value?" As of 20210909, we expand the meaning of has_mss_val, though only in nco_rgr_wgt() Now has_mss_val means does the variable use the explicitly defined missing value, or, failing that, does it use the implicitly defined missing value? Only variables that _use_ a missing value need tally and wgt_vld_out arrays mss_val_dbl is what nco_mss_val_get_dbl() returns---its meaning has not changed However, it is no longer intended to be used Instead we create mss_val_cmp_dbl, a more general value for comparison and assignment */ var_val_dbl_in=(double *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() input value buffer"); var_val_dbl_out=(double *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() output value buffer"); /* Obtain input variable */ rcd=nco_get_vara(in_id,var_id_in,dmn_srt,dmn_cnt_in,var_val_dbl_in,var_typ_rgr); /* 20210909: Begin new missing value treatment */ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); /* NB: mss_val_cmp_dbl must be defined since it is now always used by regridder (even when has_mss_val is False) For instance flg_msk_apl block, below, uses mss_val_cmp_dbl for masked fields And test for _usage_ of missing values, below, necessarily compares to mss_val_cmp_dbl If missing value is not explicitly declared, use default missing value */ if(has_mss_val) mss_val_cmp_dbl=mss_val_dbl; else mss_val_cmp_dbl=NC_FILL_DOUBLE; /* Override float/double value with appropriate default missing value for integers */ if(!has_mss_val){ switch(var_typ_out){ case NC_BYTE: mss_val_cmp_dbl=NC_FILL_BYTE; break; case NC_CHAR: mss_val_cmp_dbl=NC_FILL_CHAR; break; case NC_SHORT: mss_val_cmp_dbl=NC_FILL_SHORT; break; case NC_INT: mss_val_cmp_dbl=NC_FILL_INT; break; case NC_FLOAT: mss_val_cmp_dbl=NC_FILL_FLOAT; break; case NC_DOUBLE: mss_val_cmp_dbl=NC_FILL_DOUBLE; break; case NC_UBYTE: mss_val_cmp_dbl=NC_FILL_UBYTE; break; case NC_USHORT: mss_val_cmp_dbl=NC_FILL_USHORT; break; case NC_UINT: mss_val_cmp_dbl=NC_FILL_UINT; break; /* 20210909: Implicit type conversion generates warnings: 'long long' to 'double' changes value from -9223372036854775806 to -9223372036854775808 'unsigned long long' to 'double' changes value from 18446744073709551614 to 18446744073709551616 Warnings can be fixed with -Wimplicit-const-int-float-conversion */ case NC_INT64: mss_val_cmp_dbl=NC_FILL_INT64; break; case NC_UINT64: mss_val_cmp_dbl=NC_FILL_UINT64; break; case NC_STRING: default: nco_dfl_case_nc_type_err(); break; } /* !var_typ_in */ } /* !has_mss_val */ /* Re-initialize Boolean to True and override with False if variable _uses_ missing values */ has_mss_val=True; for(idx_in=0;idx_in<var_sz_in;idx_in++){ if(var_val_dbl_in[idx_in] == mss_val_cmp_dbl) break; } /* !idx_in */ /* If neither implicit nor explicit missing value is present, treat all values as valid */ if(idx_in == var_sz_in) has_mss_val=False; /* 20210909: End new missing value treatment */ /* Memory allocation that depends on _FillValue and input variable contents */ if(has_mss_val) tally=(int *)nco_malloc_dbg(var_sz_out*nco_typ_lng(NC_INT),fnc_nm,"Unable to malloc() tally buffer"); if(has_mss_val && flg_rnr) wgt_vld_out=(double *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ_rgr),fnc_nm,"Unable to malloc() output renormalization weight buffer"); /* Initialize output */ (void)memset(var_val_dbl_out,0,var_sz_out*nco_typ_lng(var_typ_rgr)); if(has_mss_val) (void)memset(tally,0,var_sz_out*nco_typ_lng(NC_INT)); if(wgt_vld_out) (void)memset(wgt_vld_out,0,var_sz_out*nco_typ_lng(var_typ_rgr)); /* 20150914: Intensive variables require normalization, extensive do not Intensive variables (temperature, wind speed, mixing ratio) do not depend on gridcell boundaries Extensive variables (population, counts, numbers of things) depend on gridcell boundaries Extensive variables are the exception in models, yet are commonly used for sampling information, e.g., number of photons, number of overpasses Pass extensive variable list to NCO with, e.g., --xtn=TSurfStd_ct,... 20190420: Remove languishing, unfinished intensive variable code */ clock_t tm_srt; /* [us] Microseconds at start */ clock_t tm_end; /* [us] Microseconds at end */ float tm_drn; /* [s] Seconds elapsed */ if(nco_dbg_lvl_get() >= nco_dbg_var) tm_srt=clock(); /* This first block is for "normal" variables without sub-gridscale fractions */ if(!sgs_frc_out){ /* Apply weights */ if(!has_mss_val){ if(lvl_nbr == 1){ /* Weight single-level fields without missing values */ #ifdef ENABLE_GPU # pragma omp target data map(to:col_src_adr[0:lnk_nbr],row_dst_adr[0:lnk_nbr],var_val_dbl_in[0:var_sz_in],wgt_raw[0:lnk_nbr]) map(tofrom:var_val_dbl_out[0:var_sz_out]) # pragma omp target teams distribute parallel for simd schedule(static,1) #else /* !ENABLE_GPU */ # if ( __GNUC__ >= 8 ) || ( __clang_major__ >= 8 ) # pragma omp simd # endif /* !__GNUC__ */ #endif /* !ENABLE_GPU */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) var_val_dbl_out[row_dst_adr[lnk_idx]]+=var_val_dbl_in[col_src_adr[lnk_idx]]*wgt_raw[lnk_idx]; }else{ val_in_fst=0L; val_out_fst=0L; /* Weight multi-level fields without missing values */ #ifdef ENABLE_GPU # pragma omp target data map(to:col_src_adr[0:lnk_nbr],row_dst_adr[0:lnk_nbr],var_val_dbl_in[0:var_sz_in],wgt_raw[0:lnk_nbr]) map(tofrom:var_val_dbl_out[0:var_sz_out]) # pragma omp parallel for reduction(+:val_in_fst,val_out_fst) #endif /* !ENABLE_GPU */ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ //if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(fp_stdout,"%s lvl_idx = %d val_in_fst = %li, val_out_fst = %li\n",trv.nm,lvl_idx,val_in_fst,val_out_fst); #ifdef ENABLE_GPU # pragma omp target teams distribute parallel for simd schedule(static,1) #else /* !ENABLE_GPU */ # if ( __GNUC__ >= 8 ) || ( __clang_major__ >= 8 ) # pragma omp simd # endif /* !__GNUC__ */ #endif /* !ENABLE_GPU */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) var_val_dbl_out[row_dst_adr[lnk_idx]+val_out_fst]+=var_val_dbl_in[col_src_adr[lnk_idx]+val_in_fst]*wgt_raw[lnk_idx]; val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ }else{ /* has_mss_val */ if(lvl_nbr == 1){ /* Weight single-level fields with missing values */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]; idx_out=row_dst_adr[lnk_idx]; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_cmp_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]; if(wgt_vld_out) wgt_vld_out[idx_out]+=wgt_raw[lnk_idx]; tally[idx_out]++; } /* !mss_val_cmp_dbl */ } /* !lnk_idx */ }else{ /* lvl_nbr > 1 */ val_in_fst=0L; val_out_fst=0L; /* Weight multi-level fields with missing values */ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]+val_in_fst; idx_out=row_dst_adr[lnk_idx]+val_out_fst; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_cmp_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]; if(wgt_vld_out) wgt_vld_out[idx_out]+=wgt_raw[lnk_idx]; tally[idx_out]++; } /* !mss_val_cmp_dbl */ } /* !lnk_idx */ val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ } /* !has_mss_val */ if(!has_mss_val){ /* frc_dst = frc_out = dst_frac = frac_b contains non-unity elements and normalization type is "destarea" or "dstarea" or "none" When this occurs for conservative remapping, follow "destarea" normalization procedure See SCRIP manual p. 11 and http://www.earthsystemmodeling.org/esmf_releases/public/last, specifically http://www.earthsystemmodeling.org/esmf_releases/public/last/ESMF_refdoc/node3.html#SECTION03029000000000000000 "frac_a: When a conservative regridding method is used, this contains the fraction of each source cell that participated in the regridding. When a non-conservative regridding method is used, this array is set to 0.0. frac_b: When a conservative regridding method is used, this contains the fraction of each destination cell that participated in the regridding. When a non-conservative regridding method is used, this array is set to 1.0 where the point participated in the regridding (i.e. was within the unmasked source grid), and 0.0 otherwise. If the first-order conservative interpolation method is specified ("-m conserve") then the destination field may need to be adjusted by the destination fraction (frac_b). This should be done if the normalization type is ``dstarea'' (sic, really "destarea") and if the destination grid extends outside the unmasked source grid. If it isn't known if the destination extends outside the source, then it doesn't hurt to apply the destination fraction. (If it doesn't extend outside, then the fraction will be 1.0 everywhere anyway.) The following code shows how to adjust an already interpolated destination field (dst_field) by the destination fraction. The variables n_b, and frac_b are from the weight file: ! Adjust destination field by fraction do i=1, n_b if (frac_b(i) .ne. 0.0) then dst_field(i)=dst_field(i)/frac_b(i) endif enddo" NB: Non-conservative interpolation methods (e.g., bilinear) should NOT apply this normalization (theoretically there is no danger in doing so because frc_out == 1 always for all gridcells that participate in bilinear remapping and frc_out == 0 otherwise) NCO's renormalization procedure below is similar to the ESMF-recommended procedure above. However, users can control NCO renormalization with, e.g., --rnr_thr=0.1, or override it completely with --rnr_thr=none. Moreover, frac_b == frc_dst is determined solely by solely by gridcell binary mask overlaps during weight generation. It is time-invariant and 2D. Missing values (e.g., AOD) can vary in time and can be 3D (or N-D) and so can wgt_vld_out. Hence NCO renormalization is more flexible. flg_frc_nrm (i.e., ESMF-recommended) normalization makes fields pretty for graphics, yet is non-conservative because e.g., MPAS Ocean gridcells projected onto global uniform grids would have their SSTs normalized for prettiness on coastal gridpoints, which is inherently non-conservative. 20190912: Make "ESMF renormalization" of fields without missing values (i.e., "destarea") opt-in rather than default "destarea" and frac_b = frc_dst together set flg_frc_nrm Formerly flg_frc_nrm triggered ESMF renormalization by default Now flg_frc_nrm and user-explicitly-set --rnr_thr to [0.0,1.0] must both be true to trigger it This keep conservative maps conservative by default NB: This "ESMF renormalization" normalizes by frac_b == frc_dst (not by wgt_vld_out) regardless of rnr_thr 20151018: Avoid double-normalizing by only executing fractional normalization (flg_frc_nrm) block when !has_mss_val, and valid area normalization when has_mss_val */ if(flg_frc_nrm){ /* Only renormalize when frac_b < 1.0 (because frac_b == 1.0 does nothing) */ if(flg_rnr){ /* 20190912: Only renormalize when user explicitly requests it (because renormalization is non-conservative). Prior to today, renormalization was by default, henceforth it is opt-in. */ if(lvl_nbr == 1){ /* Fractionally renormalize single-level fields without missing values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]/=frc_out[dst_idx]; }else{ /* Fractionally renormalize multi-level fields without missing values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ if(frc_out[dst_idx] != 0.0){ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ var_val_dbl_out[dst_idx+lvl_idx*grd_sz_out]/=frc_out[dst_idx]; } /* !lvl_idx */ } /* !frc_out */ } /* !dst_idx */ } /* lvl_nbr > 1 */ } /* !flg_rnr */ } /* !flg_frc_nrm */ } /* !has_mss_val */ if(has_mss_val){ /* NCL and ESMF treatment of weights and missing values described at https://www.ncl.ucar.edu/Applications/ESMF.shtml#WeightsAndMasking http://earthsystemmodeling.org/esmf_releases/non_public/ESMF_6_1_1/ESMF_refdoc/node5.html#SECTION05012600000000000000 NCO implements one of two procedures: "conservative" or "renormalized" The "conservative" algorithm uses all valid data from the input grid on the output grid Destination cells receive the weighted valid values of the source cells This is conservative because the global integrals of the source and destination fields are equal The "renormalized" algorithm divides the destination value by the sum of the valid weights This returns "reasonable" values, i.e., the mean of the valid input values However, renormalization is equivalent to extrapolating valid data to missing regions Hence the input and output integrals are unequal and the regridding is not conservative */ /* In fields with missing values, destination cells with no accumulated weight are missing value */ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(!tally[dst_idx]) var_val_dbl_out[dst_idx]=mss_val_cmp_dbl; if(flg_rnr){ // if(nco_dbg_lvl_get() >= nco_dbg_quiet) (void)fprintf(fp_stdout,"%s: DEBUG renormalization for %s uses flg_rnr block\n",nco_prg_nm_get(),var_nm); if(wgt_vld_thr == 0.0){ /* Renormalize cells with no threshold by valid accumulated weight */ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(tally[dst_idx]) var_val_dbl_out[dst_idx]/=wgt_vld_out[dst_idx]; }else{ /* Renormalize cells with threshold by valid accumulated weight if weight exceeds threshold */ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(wgt_vld_out[dst_idx] >= wgt_vld_thr){var_val_dbl_out[dst_idx]/=wgt_vld_out[dst_idx];}else{var_val_dbl_out[dst_idx]=mss_val_cmp_dbl;} } /* !wgt_vld_thr */ } /* !flg_rnr */ } /* !has_mss_val */ } /* !sgs_frc_out */ /* Variables with sub-gridscale fractions require "double-weighting" and normalization */ if(sgs_frc_out){ if(!strcmp(var_nm,sgs_frc_nm)){ /* Copy shared variable sgs_frc_out that was regridded before OpenMP loop 20190911: Reasons to copy sgs_frc_out into sgs_frc_nm data include speed, consistency, and well-definedness of sgs_frc_out. One reason to regrid sgs_frc_nm here is consistency with original, raw dataset: ELM landfrac is masked so regridding it here (rather than using sgs_frc_out) would produce a regridded dataset more identical to raw ELM output. The same can be said for CICE (I think). MPAS cellMask and timeMonthly_avg_iceAreaCell are not masked, and so should produce the same values as sgs_frc_out if regridded here. */ memcpy(var_val_dbl_out,sgs_frc_out,grd_sz_out*nco_typ_lng(var_typ_rgr)); }else if(sgs_msk_nm && !strcmp(var_nm,sgs_msk_nm)){ /* Compute binary mask directly from shared sgs_frc_out (guaranteed to be all valid values) */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]=1.0; }else{ /* !sgs_msk_nm */ /* "Double-weight" all other sub-gridscale input values by sgs_frc_in and overlap weight, normalize by sgs_frc_out */ if(!has_mss_val){ if(lvl_nbr == 1){ /* SGS-regrid single-level fields without missing values */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++) var_val_dbl_out[row_dst_adr[lnk_idx]]+=var_val_dbl_in[col_src_adr[lnk_idx]]*wgt_raw[lnk_idx]*sgs_frc_in[col_src_adr[lnk_idx]]; /* NB: MPAS-Seaice dataset sgs_frc_out is usually zero in non-polar regions */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]/=sgs_frc_out[dst_idx]; }else{ /* lvl_nbr > 1 */ /* SGS-regrid multi-level fields without missing values */ val_in_fst=0L; val_out_fst=0L; for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]; idx_out=row_dst_adr[lnk_idx]; var_val_dbl_out[idx_out+val_out_fst]+=var_val_dbl_in[idx_in+val_in_fst]*wgt_raw[lnk_idx]*sgs_frc_in[idx_in]; } /* !lnk_idx */ /* Normalize current level values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx+val_out_fst]/=sgs_frc_out[dst_idx]; val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ }else{ /* !has_mss_val */ if(lvl_nbr == 1){ /* SGS-regrid single-level fields with missing values */ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]; idx_out=row_dst_adr[lnk_idx]; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_cmp_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]*sgs_frc_in[idx_in]; tally[idx_out]++; } /* !mss_val_cmp_dbl */ } /* !lnk_idx */ /* NB: Normalization clause is complex to support sgs_frc_out from both ELM and MPAS-Seaice */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++) if(!tally[dst_idx]){var_val_dbl_out[dst_idx]=mss_val_cmp_dbl;}else{if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[dst_idx]/=sgs_frc_out[dst_idx];} }else{ /* lvl_nbr > 1 */ /* SGS-regrid multi-level fields with missing values */ val_in_fst=0L; val_out_fst=0L; for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ for(lnk_idx=0;lnk_idx<lnk_nbr;lnk_idx++){ idx_in=col_src_adr[lnk_idx]+val_in_fst; idx_out=row_dst_adr[lnk_idx]+val_out_fst; if((var_val_crr=var_val_dbl_in[idx_in]) != mss_val_cmp_dbl){ var_val_dbl_out[idx_out]+=var_val_crr*wgt_raw[lnk_idx]*sgs_frc_in[col_src_adr[lnk_idx]]; tally[idx_out]++; } /* !mss_val_cmp_dbl */ } /* !lnk_idx */ /* Normalize current level values */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ idx_out=dst_idx+val_out_fst; if(!tally[idx_out]){var_val_dbl_out[idx_out]=mss_val_cmp_dbl;}else{if(sgs_frc_out[dst_idx] != 0.0) var_val_dbl_out[idx_out]/=sgs_frc_out[dst_idx];} } /* dst_idx */ val_in_fst+=grd_sz_in; val_out_fst+=grd_sz_out; } /* !lvl_idx */ } /* lvl_nbr > 1 */ } /* !has_mss_val */ } /* !sgs_msk_nm */ } /* !sgs_frc_out */ if(nco_typ_ntg(var_typ_out)){ /* 20210407: Round, with rint(), integer fields before sending to netCDF for output Otherwise implicit type conversion will truncate (rather than round) output values This is critical for masks where rounding errors produce near integer values (e.g., 0.999...) that could then be truncated to zero by implicit conversion instead of rounded up to 1. */ if(has_mss_val){ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) if(var_val_dbl_out[dst_idx] != mss_val_cmp_dbl) var_val_dbl_out[dst_idx]=rint(var_val_dbl_out[dst_idx]); }else{ for(dst_idx=0;dst_idx<var_sz_out;dst_idx++) var_val_dbl_out[dst_idx]=rint(var_val_dbl_out[dst_idx]); } /* !has_mss_val */ } /* !nco_typ_ntg() */ if(flg_add_fll && !has_mss_val){ /* 20210604: Initialize fields without _FillValue in input file to default missing value in unmapped destination cells Otherwise empty destination cells will be zero (not _FillValue) in output file Fields with input _FillValue are already _FillValue in output where tally is zero */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ if(frc_out[dst_idx] == 0.0){ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ var_val_dbl_out[dst_idx+lvl_idx*grd_sz_out]=NC_FILL_DOUBLE; } /* !lvl_idx */ } /* !frc_out */ } /* !dst_idx */ } /* !flg_add_fll */ if(flg_msk_apl){ /* 20210607: Overwrite output values with _FillValue where destination cell is masked Same procedure regardless of whether input variables already have _FillValue NB: This is separate, and presumably independent, from above flg_add_fll loop Fields with flg_msk_apl will (harmlessly?) go through both loops */ double mss_val_msk; /* [frc] Missing value to apply where mask is false */ //if(has_mss_val) mss_val_msk=mss_val_dbl; else mss_val_msk=NC_FILL_DOUBLE; mss_val_msk=mss_val_cmp_dbl; /* [frc] Missing value to apply where mask is false */ for(dst_idx=0;dst_idx<grd_sz_out;dst_idx++){ if(msk_out[dst_idx] == 0){ for(lvl_idx=0;lvl_idx<lvl_nbr;lvl_idx++){ var_val_dbl_out[dst_idx+lvl_idx*grd_sz_out]=mss_val_msk; } /* !lvl_idx */ } /* !frc_out */ } /* !dst_idx */ } /* !flg_add_fll */ if(nco_dbg_lvl_get() >= nco_dbg_var){ tm_end=clock(); tm_drn=(float)(tm_end-tm_srt)/CLOCKS_PER_SEC; (void)fprintf(fp_stdout,"%s: INFO Compute time for %s (thread %d/%d): %g s\n",nco_prg_nm_get(),trv.nm,thr_idx,omp_get_num_threads(),tm_drn); } /* !dbg */ #pragma omp critical { /* begin OpenMP critical */ // rcd=nco_put_var(out_id,var_id_out,var_val_dbl_out,var_typ_rgr); rcd=nco_put_vara(out_id,var_id_out,dmn_srt,dmn_cnt_out,var_val_dbl_out,var_typ_rgr); } /* end OpenMP critical */ if(dmn_id_in) dmn_id_out=(int *)nco_free(dmn_id_in); if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(tally) tally=(int *)nco_free(tally); if(var_val_dbl_out) var_val_dbl_out=(double *)nco_free(var_val_dbl_out); if(var_val_dbl_in) var_val_dbl_in=(double *)nco_free(var_val_dbl_in); if(wgt_vld_out) wgt_vld_out=(double *)nco_free(wgt_vld_out); }else{ /* !trv.flg_rgr */ /* Use standard NCO copy routine for variables that are not regridded */ #pragma omp critical { /* begin OpenMP critical */ (void)nco_cpy_var_val(in_id,out_id,(FILE *)NULL,(md5_sct *)NULL,trv.nm,trv_tbl); } /* end OpenMP critical */ } /* !flg_rgr */ } /* !xtr */ } /* end (OpenMP parallel for) loop over idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"\n"); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s completion report: Variables regridded = %d (%d extensive), copied unmodified = %d, omitted = %d, created = %d\n",nco_prg_nm_get(),fnc_nm,var_rgr_nbr,var_xtn_nbr,var_cpy_nbr,var_xcl_nbr,var_crt_nbr); /* Free memory allocated for grid reading/writing */ if(area_out) area_out=(double *)nco_free(area_out); if(col_src_adr) col_src_adr=(int *)nco_free(col_src_adr); if(dmn_sz_in_int) dmn_sz_in_int=(int *)nco_free(dmn_sz_in_int); if(dmn_sz_out_int) dmn_sz_out_int=(int *)nco_free(dmn_sz_out_int); if(frc_out) frc_out=(double *)nco_free(frc_out); if(lat_bnd_out) lat_bnd_out=(double *)nco_free(lat_bnd_out); if(lat_crn_out) lat_crn_out=(double *)nco_free(lat_crn_out); if(lat_ctr_out) lat_ctr_out=(double *)nco_free(lat_ctr_out); if(lat_ntf_out) lat_ntf_out=(double *)nco_free(lat_ntf_out); if(lat_wgt_out) lat_wgt_out=(double *)nco_free(lat_wgt_out); if(lon_bnd_out) lon_bnd_out=(double *)nco_free(lon_bnd_out); if(lon_crn_out) lon_crn_out=(double *)nco_free(lon_crn_out); if(lon_ctr_out) lon_ctr_out=(double *)nco_free(lon_ctr_out); if(lon_ntf_out) lon_ntf_out=(double *)nco_free(lon_ntf_out); if(msk_out) msk_out=(int *)nco_free(msk_out); if(row_dst_adr) row_dst_adr=(int *)nco_free(row_dst_adr); if(sgs_frc_nm) sgs_frc_nm=(char *)nco_free(sgs_frc_nm); if(sgs_frc_in) sgs_frc_in=(double *)nco_free(sgs_frc_in); if(sgs_frc_out) sgs_frc_out=(double *)nco_free(sgs_frc_out); if(sgs_msk_nm) sgs_msk_nm=(char *)nco_free(sgs_msk_nm); if(wgt_raw) wgt_raw=(double *)nco_free(wgt_raw); return rcd; } /* end nco_rgr_wgt() */ void nco_bsl_zro /* Return Bessel function zeros */ (const int bsl_zro_nbr, /* O [nbr] Order of Bessel function */ double * const bsl_zro) /* O [frc] Bessel zero */ { /* Purpose: Return Bessel function zeros Source: CCM code /fs/cgd/csm/models/atm/ccm3.5.8/src/ccmlsm_share/bsslzr.F Return bsl_zro_nbr zeros (or if bsl_zro_nbr > 50, approximate zeros), of the Bessel function j0 First 50 zeros are given exactly, and remaining zeros are computed by extrapolation, and therefore are not exact Original version: CCM1 Standardized: J. Rosinski, June 1992 Reviewed: J. Hack, D. Williamson, August 1992 Reviewed: J. Hack, D. Williamson, April 1996 Modified 19970123 by Jim Rosinski to use double precision arithmetic ~2000: Converted to Fortran9X by C. Zender, changed all real*16 statements to double precision (real*8) 20150530: Converted to C99 by C. Zender */ const char fnc_nm[]="nco_bsl_zro()"; /* [sng] Function name */ const double pi=M_PI; // [frc] 3 const double bsl_zro_tbl[]={ // Zeros of Bessel functions of order 1 to 50 -1.e36, 2.4048255577, 5.5200781103, 8.6537279129, 11.7915344391, 14.9309177086, 18.0710639679, 21.2116366299, 24.3524715308, 27.4934791320, 30.6346064684, 33.7758202136, 36.9170983537, 40.0584257646, 43.1997917132, 46.3411883717, 49.4826098974, 52.6240518411, 55.7655107550, 58.9069839261, 62.0484691902, 65.1899648002, 68.3314693299, 71.4729816036, 74.6145006437, 77.7560256304, 80.8975558711, 84.0390907769, 87.1806298436, 90.3221726372, 93.4637187819, 96.6052679510, 99.7468198587, 102.8883742542, 106.0299309165, 109.1714896498, 112.3130502805, 115.4546126537, 118.5961766309, 121.7377420880, 124.8793089132, 128.0208770059, 131.1624462752, 134.3040166383, 137.4455880203, 140.5871603528, 143.7287335737, 146.8703076258, 150.0118824570, 153.1534580192, 156.2950342685}; const int bsl_zro_tbl_nbr_max=50; /* [nbr] */ int bsl_idx; /* [idx] Counting index */ /* Main Code */ if(nco_dbg_lvl_get() >= nco_dbg_sbr) (void)fprintf(stdout,"%s: DEBUG Entering %s\n",nco_prg_nm_get(),fnc_nm); /* NB: Initialize bsl_zro[0] but (in C) never use it Initialization prevents uninitialized memory warnings */ for(bsl_idx=0;bsl_idx<=bsl_zro_nbr;bsl_idx++) if(bsl_idx <= bsl_zro_tbl_nbr_max) bsl_zro[bsl_idx]=bsl_zro_tbl[bsl_idx]; if(bsl_zro_nbr > bsl_zro_tbl_nbr_max) for(bsl_idx=bsl_zro_tbl_nbr_max+1;bsl_idx<=bsl_zro_nbr;bsl_idx++) bsl_zro[bsl_idx]=bsl_zro[bsl_idx-1]+pi; if(nco_dbg_lvl_get() == nco_dbg_old){ (void)fprintf(stdout,"%s: DEBUG %s reports bsl_zro_nbr = %d\n",nco_prg_nm_get(),fnc_nm,bsl_zro_nbr); (void)fprintf(stdout,"idx\tbsl_zro\n"); for(bsl_idx=1;bsl_idx<=bsl_zro_nbr;bsl_idx++) (void)fprintf(stdout,"%d\t%g\n",bsl_idx,bsl_zro[bsl_idx]); } /* endif dbg */ return; } /* end nco_bsl_zro() */ void nco_lat_wgt_gss /* [fnc] Compute and return sine of Gaussian latitudes and their weights */ (const int lat_nbr, /* I [nbr] Latitude number */ const nco_bool flg_s2n, /* I [enm] Latitude grid-direction is South-to-North */ double * const lat_sin, /* O [frc] Sine of latitudes */ double * const wgt_Gss) /* O [frc] Gaussian weights */ { /* Purpose: Compute and return sine of Gaussian latitudes and their weights Returned arrays are ordered south-to-north (S->N), not (N->S) Source: CCM /fs/cgd/csm/models/atm/ccm3.5.8/src/ccmlsm_share/gauaw.F Calculate sine of latitudes lat_sin(lat_nbr) and weights wgt_Gss(lat_nbr) for Gaussian quadrature Algorithm described in Davis and Rabinowitz, Journal of Research of the NBS, V 56, Jan 1956 Zeros of Bessel function j0, obtained from nco_bsl_zro(), are first guess for abscissae Original version: CCM1 Standardized: L. Bath, Jun 1992 L. Buja, Feb 1996 Reviewed: D. Williamson, J. Hack, Aug 1992 D. Williamson, J. Hack, Feb 1996 19970123 Modified by Jim Rosinski to use real*16 arithmetic in order to achieve (nearly) identical weights and latitudes on all machines. ~2000: Converted to Fortran9X by C. Zender, changed all real*16 statements to double precision (real*8) 20150530: Converted to C99 by C. Zender 20150725: Verified against tabulation at http://pomax.github.io/bezierinfo/legendre-gauss.html#n64 */ const char fnc_nm[]="nco_lat_wgt_gss()"; /* [sng] Function name */ const double eps_rlt=1.0e-16; // Convergence criterion (NB: Threshold was 1.0d-27 in real*16, 1.0e-15 fine for real*8, 1.0e-16 pushes double precision to the brink) const double pi=M_PI; // [frc] 3 const int itr_nbr_max=20; // [nbr] Maximum number of iterations double c_cff; // Constant combination coefficient double lat_idx_dbl; // Latitude index, double precision double lat_nnr_idx_dbl; // Inner latitude index, double precision double lat_nbr_dbl; // [nbr] Number of latitudes, double precision double pk=double_CEWI; // Polynomial double pkm1; // Polynomial double pkm2; // Polynomial double pkmrk; // Polynomial double sp; // Current iteration latitude increment double xz; // Abscissa estimate double cos_arg; // Intermediate parameter introduced while attempting to eliminate valgrind "uninitialised value" warnings int itr_cnt; // Iteration counter int lat_idx; // [idx] Counting index (latitude) int lat_sym_idx; // [idx] Counting index (symmetric latitude) int lat_nnr_idx; // [idx] Counting index (inner latitude loop) int lat_nbr_rcp2; // lat_nbr/2 (number of latitudes in hemisphere) double *lat_sin_p1; // Sine of Gaussian latitudes double precision double *wgt_Gss_p1; // Gaussian weights double precision /* Main Code */ if(nco_dbg_lvl_get() >= nco_dbg_sbr) (void)fprintf(stdout,"%s: DEBUG Entering %s\n",nco_prg_nm_get(),fnc_nm); /* Arrays with Fortran indexing (indicated by "plus one" = "_p1") keep numerical algorithm in C identical to Fortran */ lat_sin_p1=(double *)nco_malloc((lat_nbr+1)*sizeof(double)); // Sine of Gaussian latitudes double precision wgt_Gss_p1=(double *)nco_malloc((lat_nbr+1)*sizeof(double)); // Gaussian weights double precision /* Use Newton iteration to find abscissae */ c_cff=0.25*(1.0-4.0/(pi*pi)); lat_nbr_dbl=lat_nbr; lat_nbr_rcp2=lat_nbr/2; // NB: Integer arithmetic (void)nco_bsl_zro(lat_nbr_rcp2,lat_sin_p1); for(lat_idx=1;lat_idx<=lat_nbr_rcp2;lat_idx++){ // NB: Loop starts at 1 // 20150713: Introduce intermediate parameter cos_arg in attempt to eliminate valgrind "uninitialised value" warnings emitted by cos() (actually __cos_sse()) // Warnings occur with gcc-compiled code, not with clang-compiled code cos_arg=lat_sin_p1[lat_idx]/sqrt((lat_nbr_dbl+0.5)*(lat_nbr_dbl+0.5)+c_cff); xz=cos(cos_arg); /* First approximation to xz */ itr_cnt=0; /* goto label_73 */ label_73: pkm2=1.0; pkm1=xz; if(++itr_cnt > itr_nbr_max){ (void)fprintf(stdout,"%s: ERROR %s reports convergence only %g after %d iterations for lat_idx = %d\n",nco_prg_nm_get(),fnc_nm,fabs(sp),itr_nbr_max,lat_idx); nco_exit(EXIT_FAILURE); } /* endif */ /* Compute Legendre polynomial */ for(lat_nnr_idx=2;lat_nnr_idx<=lat_nbr;lat_nnr_idx++){ lat_nnr_idx_dbl=lat_nnr_idx; pk=((2.0*lat_nnr_idx_dbl-1.0)*xz*pkm1-(lat_nnr_idx_dbl-1.0)*pkm2)/lat_nnr_idx_dbl; pkm2=pkm1; pkm1=pk; } /* end inner loop over lat_nnr */ pkm1=pkm2; pkmrk=(lat_nbr_dbl*(pkm1-xz*pk))/(1.0-xz*xz); sp=pk/pkmrk; xz=xz-sp; /* NB: Easy to introduce bug here by not replacing Fortran abs() with C fabs() */ if(fabs(sp) > eps_rlt) goto label_73; lat_sin_p1[lat_idx]=xz; wgt_Gss_p1[lat_idx]=(2.0*(1.0-xz*xz))/((lat_nbr_dbl*pkm1)*(lat_nbr_dbl*pkm1)); } /* end outer loop over lat */ if(lat_nbr != lat_nbr_rcp2*2){ /* When lat_nbr is odd, compute weight at Equator */ lat_sin_p1[lat_nbr_rcp2+1]=0.0; pk=2.0/(lat_nbr_dbl*lat_nbr_dbl); for(lat_idx=2;lat_idx<=lat_nbr;lat_idx+=2){ lat_idx_dbl=lat_idx; pk=pk*lat_idx_dbl*lat_idx_dbl/((lat_idx_dbl-1.0)*(lat_idx_dbl-1.0)); } /* end loop over lat */ wgt_Gss_p1[lat_nbr_rcp2+1]=pk; } /* endif lat_nbr is odd */ /* Complete sets of abscissas and weights, using symmetry properties */ for(lat_idx=1;lat_idx<=lat_nbr_rcp2;lat_idx++){ lat_sym_idx=lat_nbr-lat_idx+1; lat_sin_p1[lat_sym_idx]=-lat_sin_p1[lat_idx]; wgt_Gss_p1[lat_sym_idx]=wgt_Gss_p1[lat_idx]; } /* end loop over lat */ /* Shift by one to remove Fortran offset in p1 arrays */ //memcpy(lat_sin,lat_sin_p1,lat_nbr*sizeof(double)); //memcpy(wgt_Gss,wgt_Gss_p1,lat_nbr*sizeof(double)); /* Reverse and shift arrays because original CCM code algorithm computes latitudes from north-to-south Shift by one to remove Fortran offset in p1 arrays */ if(flg_s2n){ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ lat_sin[lat_idx]=lat_sin_p1[lat_nbr-lat_idx]; wgt_Gss[lat_idx]=wgt_Gss_p1[lat_nbr-lat_idx]; } /* end loop over lat */ }else{ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ lat_sin[lat_idx]=lat_sin_p1[lat_idx+1]; wgt_Gss[lat_idx]=wgt_Gss_p1[lat_idx+1]; } /* end loop over lat */ } /* !flg_s2n */ if(nco_dbg_lvl_get() == nco_dbg_old){ (void)fprintf(stdout,"%s: DEBUG %s reports lat_nbr = %d\n",nco_prg_nm_get(),fnc_nm,lat_nbr); (void)fprintf(stdout,"idx\tasin\tngl_rad\tngl_dgr\tgw\n"); for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) (void)fprintf(stdout,"%d\t%g\t%g\t%g%g\n",lat_idx,lat_sin[lat_idx],asin(lat_sin[lat_idx]),180.0*asin(lat_sin[lat_idx])/pi,wgt_Gss[lat_idx]); } /* endif dbg */ if(wgt_Gss_p1) wgt_Gss_p1=(double *)nco_free(wgt_Gss_p1); if(lat_sin_p1) lat_sin_p1=(double *)nco_free(lat_sin_p1); return; } /* end nco_lat_wgt_gss() */ void nco_sph_plg_area /* [fnc] Compute area of spherical polygon */ (rgr_sct * const rgr, /* I [sct] Regridding structure */ const double * const lat_bnd, /* [dgr] Latitude boundaries of rectangular grid */ const double * const lon_bnd, /* [dgr] Longitude boundaries of rectangular grid */ const long col_nbr, /* [nbr] Number of columns in grid */ const int bnd_nbr, /* [nbr] Number of bounds in gridcell */ double * const area) /* [sr] Gridcell area */ { /* Purpose: Compute area of spherical polygon */ /* Computing triangular area accurately is hard in corner cases Spherical triangle suffer from at least as many issues as planar, which are described by "Miscalculating Area and Angles of a Needle-like Triangle" by W. Kahan, UC Berkeley In particular, the Law of Cosines and Heron's formula can be ill-conditioned For spherical triangles L'Huilier's Theorem is superior to Girard's Formula: http://mathworld.wolfram.com/LHuiliersTheorem.html Girard's formula depends on pi-minus-angle and angle is usually quite small in our applications so precision would be lost L'Huilier's theorem depends only on angles (a,b,c) and semi-perimeter (s) and is well-conditioned for small angles semi-perimeter = half-perimeter of triangle = 0.5*(a+b+c) Spherical Excess (SE) difference between the sum of the angles of a spherical triangle area and a planar triangle area with same interior angles (that sum to pi) SE is also the solid angle subtended by the spherical triangle and that's, well, astonishing and pretty cool Wikipedia shows a better SE formula for triangles that are ill-conditioned for L'Huilier's formula because a = b ~ 0.5c https://en.wikipedia.org/wiki/Spherical_trigonometry#Area_and_spherical_excess See also interesting discussion of L'Huilier by Charles Karney who suggests his own alternative: http://osgeo-org.1560.x6.nabble.com/Area-of-a-spherical-polygon-td3841625.html The discussion mentions Mil94 Robert D. Miller, Computing the area of a spherical polygon, Graphic Gems IV, chapter II.4, pages 132-137. http://books.google.com/books?id=CCqzMm_-WucC&pg=PA132&lpg=PA132&dq=miller+area+spherical+polygon+gems&source=bl&ots=mrnvZ6NJcm&sig=CMg8eaD8dzP5snMaPeCQzgoFWUk&hl=sv&ei=4G-YTKv5GsWZOI-mmZQP&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBQQ6AEwAA#v=onepage&q&f=false Mil94 contains similar ideas to my method for spherical polygons (decomposing into adjacent multiple triangles from single vertex) However, his method places single vertex at pole, then adds signed areas to obtain full polygon area His method may suffer from degraded precision because of roundoff error and long side-lengths So-called "proper" spherical triangle are those for which all angles are less than pi, so a+b+c<3*pi Cartesian coordinates of (lat,lon)=(theta,phi) are (x,y,z)=(cos(theta)*cos(phi),cos(theta)*sin(phi),sin(theta)) Dot-product rule for vectors gives interior angle/arc length between two points: cos(a)=u dot v=cos(theta1)*cos(phi1)*cos(theta2)*cos(phi2)+cos(theta1)*sin(phi1)*cos(theta2)*sin(phi2)+sin(theta1)*sin(theta2) Spherical law of cosines relates interior angles/arc-lengths (a,b,c) to surface angles (A,B,C) in spherical triangle: https://en.wikipedia.org/wiki/Spherical_law_of_cosines cos(a)=cos(b)*cos(c)+sin(b)*sin(c)*cos(A) cos(b)=cos(c)*cos(a)+sin(c)*sin(a)*cos(B) cos(c)=cos(a)*cos(b)+sin(a)*sin(b)*cos(C) cos(A)=[cos(a)-cos(b)*cos(c)]/[sin(b)*sin(c)] cos(B)=[cos(b)-cos(c)*cos(a)]/[sin(c)*sin(a)] cos(C)=[cos(c)-cos(a)*cos(b)]/[sin(a)*sin(b)] Bounds information on unstructured grids will use bounds_nbr=maximum(vertice_nbr) Unused vertices are stored as either repeated points (ACME does this) or, conceiveably, as missing values Given (lat,lon) for N-points algorithm to find area of spherical polygon is: 1. Any decomposition, Girard areas: Loses precision due to mismatch between pi and small spherical excesses A. Find interior angles/arc-lengths (a,b,c,d...) using spherical law of cosines along each edge B. Apply generalized Girard formula SE_n = Sum(A_n) - (N-2) - pi 2. CSZ decomposition (N-2 triangles) with L'Huilier areas, Convert polygon into triangles by cycling spoke through all sides from common apex This method requires computation of N-2 (not N) triangles, though fewer sides due to optimization It works on all convex polygons (interior angles less than 180) but not, in general, concave polygons Whether it works or not on concave polygons depends upon their exact shape and the choice of apex point A. First three non-identical points form first triangle with sides A,B,C (first+second point define A, etc.) i. First vertice anchors all triangles ii. Third vertice of preceding triangle becomes second vertice of next triangle iii. Next non-identical point becomes last vertice of next triangle iv. Side C of previous triangle is side A of next triangle B. For each triangle, compute area with L'Huilier formula unless A = B ~ 0.5*C then use SAS formula 3. centroidal decomposition, N triangle version by Taylor, L'Huilier areas: Compute polygon centroid and treat this as hub from which spokes are drawn to all vertices This method requires computation of N triangles, though fewer sides due to optimization Moreover, it works on all convex polygons and on slightly concave polygons Centroid/hub has clear view of interior of most simple concave polygons 4. Any decomposition but with exact RLL grids by Zender and Agress 20160918 A. Decompose polygon into triangles via any method (e.g., method 2 or 3 above) B. Determine whether triangle is spherical or contains RLL (constant latitude) C. Spherical triangles use L'Huilier, RLL triangles use series expansion */ const char fnc_nm[]="nco_sph_plg_area()"; const double dgr2rdn=M_PI/180.0; int bnd_nbr_ttl; /* [nbr] Number of bounds in gridcell accounting for possibility of centroid information */ long idx; /* [idx] Counting index for unrolled grids */ short int bnd_idx; /* Shift to this method once we pass rgr into nco_sph_plg_area() */ nco_bool flg_mth_csz=False; /* [flg] Use CSZ's advancing polygon bisector method */ nco_bool flg_mth_ctr=False; /* [flg] Use centroid method to compute polygon area */ nco_edg_typ_enm edg_typ; /* [enm] Arc-type for triangle edges */ nco_ply_tri_mth_typ_enm ply_tri_mth; /* [enm] Polygon decomposition method */ if(rgr->edg_typ == nco_edg_nil) rgr->edg_typ=nco_edg_gtc; edg_typ=rgr->edg_typ; /* [enm] Arc-type for triangle edges */ ply_tri_mth=rgr->ply_tri_mth; /* [enm] Polygon decomposition method */ if(ply_tri_mth == nco_ply_tri_mth_csz) flg_mth_csz=True; if(ply_tri_mth == nco_ply_tri_mth_ctr) flg_mth_ctr=True; assert(flg_mth_ctr != flg_mth_csz); bnd_nbr_ttl=bnd_nbr; // Allocate space for one extra boundary to store centroid information if necessary if(flg_mth_ctr) bnd_nbr_ttl=bnd_nbr+1; double *lat_bnd_rdn=NULL_CEWI; /* [rdn] Latitude boundaries of rectangular destination grid */ double *lon_bnd_rdn=NULL_CEWI; /* [rdn] Longitude boundaries of rectangular destination grid */ double *lat_bnd_sin=NULL_CEWI; /* [frc] Sine of latitude boundaries of rectangular destination grid */ double *lon_bnd_sin=NULL_CEWI; /* [frc] Sine of longitude boundaries of rectangular destination grid */ double *lat_bnd_cos=NULL_CEWI; /* [frc] Cosine of latitude boundaries of rectangular destination grid */ double *lon_bnd_cos=NULL_CEWI; /* [frc] Cosine of longitude boundaries of rectangular destination grid */ /* Allocate one extra space for some arrays to store polygon centroid values for each column for ply_tri_mth=ctr */ lon_bnd_rdn=(double *)nco_malloc(col_nbr*bnd_nbr_ttl*sizeof(double)); lat_bnd_rdn=(double *)nco_malloc(col_nbr*bnd_nbr_ttl*sizeof(double)); lon_bnd_cos=(double *)nco_malloc(col_nbr*bnd_nbr*sizeof(double)); lat_bnd_cos=(double *)nco_malloc(col_nbr*bnd_nbr_ttl*sizeof(double)); lon_bnd_sin=(double *)nco_malloc(col_nbr*bnd_nbr*sizeof(double)); lat_bnd_sin=(double *)nco_malloc(col_nbr*bnd_nbr*sizeof(double)); memcpy(lat_bnd_rdn,lat_bnd,col_nbr*bnd_nbr*sizeof(double)); memcpy(lon_bnd_rdn,lon_bnd,col_nbr*bnd_nbr*sizeof(double)); for(idx=0;idx<col_nbr*bnd_nbr;idx++){ lon_bnd_rdn[idx]*=dgr2rdn; lat_bnd_rdn[idx]*=dgr2rdn; lon_bnd_cos[idx]=cos(lon_bnd_rdn[idx]); lat_bnd_cos[idx]=cos(lat_bnd_rdn[idx]); lon_bnd_sin[idx]=sin(lon_bnd_rdn[idx]); lat_bnd_sin[idx]=sin(lat_bnd_rdn[idx]); } /* !idx */ double area_smc_crc; /* [sr] Small-circle correction to spherical triangle area */ double area_smc; /* [sr] Gridcell area allowing for latitude-triangles */ double area_ttl; /* [sr] Total area of input polygon list assuming spherical triangles */ double area_smc_ttl; /* [sr] Total area of input polygon list allowing for latitude-triangles */ double area_smc_crc_ttl; /* [sr] Latitude-triangle correction (should be small) to total area of input polygon list */ double area_smc_crc_abs_ttl; /* [sr] Latitude-triangle absolute correction (no compensation of positive/negative contributions, should be no smaller than above) to total area of input polygon list */ double lat_ctr; /* [dgr] Latitude of polygon centroid */ double lon_ctr; /* [dgr] Longitude of polygon centroid */ double lat_ctr_rdn; /* [rdn] Latitude of polygon centroid */ double lon_ctr_rdn; /* [rdn] Longitude of polygon centroid */ double lat_ctr_cos; /* [frc] Cosine latitude of polygon centroid */ double lat_dlt; /* [rdn] Latitudinal difference */ double lon_dlt; /* [rdn] Longitudinal difference */ double ngl_a; /* [rdn] Interior angle/great circle arc a */ double ngl_b; /* [rdn] Interior angle/great circle arc b */ double ngl_c; /* [rdn] Interior angle/great circle arc c */ double ngl_ltr_a; /* [rdn] Interior angle/small circle arc a, canonical latitude-triangle geometry */ double ngl_ltr_b; /* [rdn] Interior angle/great circle arc b, canonical latitude-triangle geometry */ double ngl_ltr_c; /* [rdn] Interior angle/great circle arc c, canonical latitude-triangle geometry */ double prm_smi; /* [rdn] Semi-perimeter of triangle */ double sin_hlf_tht; /* [frc] Sine of half angle/great circle arc theta connecting two points */ double xcs_sph; /* [sr] Spherical excess */ int tri_nbr; /* [nbr] Number of triangles in polygon */ long bnd_vld_nbr=NC_MIN_INT; /* [idx] Number of valid (non-duplicative) vertices in each triangle */ long *a_idx; /* [idx] Point A 1-D indices for each triangle in polygon */ long *b_idx; /* [idx] Point B 1-D indices for each triangle in polygon */ long *c_idx; /* [idx] Point C 1-D indices for each triangle in polygon */ long *vrt_vld=NULL; /* [idx] Absolute 1-D indices of valid vertices */ long idx_a; /* [idx] Point A 1-D index */ long idx_b; /* [idx] Point B 1-D index */ long idx_c; /* [idx] Point C 1-D index */ nco_bool flg_sas_ndl=False; /* [flg] L'Huilier's formula will fail due to needle where one side exceeds semi-perimeter */ nco_bool flg_sas_isc=False; /* [flg] L'Huilier's formula is ill-conditioned due to flat, near-isoceles triangle */ nco_bool flg_sas_a=False; /* [flg] Use SAS triangle formula with central angle a */ nco_bool flg_sas_b=False; /* [flg] Use SAS triangle formula with central angle b */ nco_bool flg_sas_c=False; /* [flg] Use SAS triangle formula with central angle c */ nco_bool flg_ply_has_smc; /* [flg] Any triangle in polygon has small-circle edge */ nco_bool flg_tri_crr_smc; /* [flg] Current triangle has small_circle edge */ /* Initialize global accumulators */ area_ttl=0.0; area_smc_ttl=0.0; area_smc_crc_ttl=0.0; area_smc_crc_abs_ttl=0.0; for(long col_idx=0;col_idx<col_nbr;col_idx++){ /* Initialize local properties and accumulators for this cell/polygon */ flg_ply_has_smc=False; ngl_c=double_CEWI; /* Otherwise compiler unsure ngl_c is initialized first use */ area[col_idx]=0.0; area_smc=0.0; tri_nbr=0; if(col_idx == 0){ a_idx=(long *)nco_calloc(bnd_nbr,sizeof(long)); b_idx=(long *)nco_calloc(bnd_nbr,sizeof(long)); c_idx=(long *)nco_calloc(bnd_nbr,sizeof(long)); vrt_vld=(long *)nco_calloc(bnd_nbr,sizeof(long)); } /* !col_idx */ /* Safety re-initialization to ease debugging, not strictly necessary */ for(bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++){ vrt_vld[bnd_idx]=NC_MIN_INT; a_idx[bnd_idx]=NC_MIN_INT; b_idx[bnd_idx]=NC_MIN_INT; c_idx[bnd_idx]=NC_MIN_INT; } /* !bnd_idx */ if(flg_mth_ctr){ double lon_dff; /* [dgr] Longitude difference */ long bnd_srt_idx; /* [idx] Absolute starting index of vertices in polygon */ long bnd_idx; /* [idx] Offset of current valid vertex index from starting index */ long bnd_vld_idx; /* [idx] Absolute index of last valid vertex */ /* First vertice is always valid */ bnd_srt_idx=bnd_nbr*col_idx; bnd_vld_idx=bnd_srt_idx; vrt_vld[0]=bnd_vld_idx; lat_ctr=lat_bnd[bnd_srt_idx]; lon_ctr=lon_bnd[bnd_srt_idx]; bnd_vld_nbr=1; /* First guess for next valid index */ bnd_idx=1; /* bnd_idx labels offset from first vertex of next valid (i.e., non-duplicative) vertex */ while(bnd_idx<bnd_nbr){ /* Skip repeated points that must occur when polygon has fewer than allowed vertices */ while(lon_bnd[bnd_vld_idx] == lon_bnd[bnd_srt_idx+bnd_idx] && lat_bnd[bnd_srt_idx] == lat_bnd[bnd_srt_idx+bnd_idx]){ /* Next valid vertice must not duplicate first vertex */ bnd_idx++; /* Have we already found all valid vertices? */ if(bnd_idx == bnd_nbr) break; } /* !while */ /* Jump to normalization when all valid vertices found */ if(bnd_idx == bnd_nbr) break; /* Current vertex is valid (non-duplicative) */ bnd_vld_idx=bnd_srt_idx+bnd_idx; vrt_vld[bnd_vld_nbr]=bnd_vld_idx; bnd_vld_nbr++; if(nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: DEBUG %s reports centroidal decomposition col_idx=%lu, bnd_nbr=%d, bnd_idx=%ld, bnd_vld_idx=%ld, bnd_vld_nbr=%ld\n",nco_prg_nm_get(),fnc_nm,col_idx,bnd_nbr,bnd_idx,bnd_vld_idx,bnd_vld_nbr); assert(bnd_vld_nbr <= bnd_nbr); lat_ctr+=lat_bnd[bnd_vld_idx]; lon_ctr+=lon_bnd[bnd_vld_idx]; lon_dff=lon_bnd[bnd_vld_idx]-lon_bnd[0]; if(lon_dff >= 180.0){ lon_ctr-=360.0; }else if(lon_dff <= -180.0){ lon_ctr+=360.0; } /* !lon_dff */ /* Search for next valid vertice in next iteration */ bnd_idx++; } /* !bnd_idx */ /* Compute centroid */ lat_ctr/=bnd_vld_nbr; lon_ctr/=bnd_vld_nbr; /* Centroid can become point A of bnd_nbr polygons or optimize algorithm: 1. Skip sub-dividing polygon into centroid-based triangles for bnd_vld_nbr == 3 2. Split quadrilaterals into two (non-centroid) triangles for bnd_vld_nbr == 4 3. Use full centroid-based triangle algorithm for bnd_vld_nbr >= 5 */ lat_ctr_rdn=lat_ctr*dgr2rdn; lon_ctr_rdn=lon_ctr*dgr2rdn; lat_ctr_cos=cos(lat_ctr_rdn); /* Place centroid values in extended arrays for easy access */ lat_bnd_rdn[(col_idx+1)*bnd_nbr_ttl-1L]=lat_ctr_rdn; lon_bnd_rdn[(col_idx+1)*bnd_nbr_ttl-1L]=lon_ctr_rdn; lat_bnd_cos[(col_idx+1)*bnd_nbr_ttl-1L]=lat_ctr_cos; /* Polygon centroid and valid vertices are now known */ assert(bnd_vld_nbr > 2); if(bnd_vld_nbr == 3){ /* Three vertices only means polygon is already decomposed into a triangle */ tri_nbr=1; a_idx[0]=vrt_vld[0]; b_idx[0]=vrt_vld[1]; c_idx[0]=vrt_vld[2]; }else if(bnd_vld_nbr == 4){ /* Bisect quadrilateral into two triangles rather than use centroid and have four triantles */ tri_nbr=2; a_idx[0]=vrt_vld[0]; b_idx[0]=vrt_vld[1]; c_idx[0]=vrt_vld[2]; a_idx[1]=vrt_vld[0]; /* NB: Order is important. This way side C of triangle[0] = side A of trangle[1] */ b_idx[1]=vrt_vld[2]; c_idx[1]=vrt_vld[3]; }else if(bnd_vld_nbr >= 5){ /* Centroid method has as many triangles as valid vertices */ tri_nbr=bnd_vld_nbr; for(int tri_idx=0;tri_idx<tri_nbr;tri_idx++){ a_idx[tri_idx]=(col_idx+1)*bnd_nbr_ttl-1L; /* A is always centroid, store values at end of arrays */ b_idx[tri_idx]=vrt_vld[tri_idx]; c_idx[tri_idx]=vrt_vld[(tri_idx+1)%tri_nbr]; } /* !tri_idx */ } /* !bnd_vld_nbr */ } /* !flg_mth_ctr */ if(flg_mth_csz){ /* A is always first vertice of all triangles */ idx_a=bnd_nbr*col_idx; /* Start search for B at next vertice */ bnd_idx=1; /* bnd_idx labels offset from point A of potential location of triangle points B and C We know that bnd_idx(A) == 0, bnd_idx(B) < bnd_nbr-1, bnd_idx(C) < bnd_nbr */ while(bnd_idx<bnd_nbr-1){ /* Only first triangle must search for B, subsequent triangles recycle previous C as current B */ if(tri_nbr == 0){ /* Skip repeated points that must occur when polygon has fewer than allowed vertices */ /* 20200115: Prior to today we never skipped polar points (same latitudes but different longitudes) That worked fine in practice for spherical triangles partly because triangles from CSZ decomposition (aka hub-and-spoke decomposition) are additive, even with multiple points on the same great circle, and partly due to luck (a starting vertex surrounded by points on the same geodesic would break it). Moreover, repeated polar points pose no issues for L'Huilier's (or Girard's) method which depends only on the interior angles and side lengths, not the longitudes of polar points. Small circles change that last part, and we must now eliminate repeated polar points. */ if(edg_typ == nco_edg_smc){ /* Skip repeated numerically identical points */ while(lon_bnd[idx_a] == lon_bnd[idx_a+bnd_idx] && lat_bnd[idx_a] == lat_bnd[idx_a+bnd_idx]){ /* Next vertice may not duplicate A */ bnd_idx++; /* If there is no room for C then all triangles found */ if(bnd_idx == bnd_nbr-1) break; } /* !while */ /* Skip geometrically identical (i.e., repeated polar) points */ while((fabs(lat_bnd[idx_a]) == 90.0) && (fabs(lat_bnd[idx_a+bnd_idx]) == 90.0)){ bnd_idx++; if(bnd_idx == bnd_nbr-1) break; } /* !while */ }else if(edg_typ != nco_edg_smc){ /* Spherical polygongs can use simpler, pre-20200116 algorithm to eliminate repeated points */ while(lon_bnd[idx_a] == lon_bnd[idx_a+bnd_idx] && lat_bnd[idx_a] == lat_bnd[idx_a+bnd_idx]){ /* Next vertice may not duplicate A */ bnd_idx++; /* If there is no room for C then all triangles found */ if(bnd_idx == bnd_nbr-1) break; } /* !while */ }else{ abort(); } /* !edg_typ */ /* Jump to next column when all triangles found */ if(bnd_idx == bnd_nbr-1) break; } /* !tri_nbr */ idx_b=idx_a+bnd_idx; /* Search for C at next vertice */ bnd_idx++; /* fxm */ while(lon_bnd[idx_b] == lon_bnd[idx_a+bnd_idx] && lat_bnd[idx_b] == lat_bnd[idx_a+bnd_idx]){ /* Next vertice may not duplicate B */ bnd_idx++; /* If there is no room for C then all triangles found */ if(bnd_idx == bnd_nbr) break; } /* !while */ /* Jump to next column when all triangles found */ if(bnd_idx == bnd_nbr) break; idx_c=idx_a+bnd_idx; /* Valid triangle, vertices are known and labeled */ a_idx[tri_nbr]=idx_a; b_idx[tri_nbr]=idx_b; c_idx[tri_nbr]=idx_c; tri_nbr++; /* Begin search for next B at current C */ bnd_idx=idx_c-idx_a; } /* !bnd_idx */ } /* !flg_mth_csz */ /* Triangles are known for requested decomposition method Compute and accumulate their area Optimized algorithm recycles previous arc c as current arc a (after first triangle) */ for(int tri_idx=0;tri_idx<tri_nbr;tri_idx++){ idx_a=a_idx[tri_idx]; idx_b=b_idx[tri_idx]; idx_c=c_idx[tri_idx]; if(nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: DEBUG %s reports triangle vertices: col_idx=%lu, tri_idx=%d, idx_a=%ld, idx_b=%ld, idx_c=%ld\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,idx_a,idx_b,idx_c); /* Compute interior angle/great circle arc a for first triangle; subsequent triangles recycle previous arc c */ if(tri_idx == 0){ /* 20150831: Test by computing ncol=0 area in conus chevrons grid, compare to MAT results ncremap -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/257x512_SCRIP.20150901.nc -m ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.20150901.nc ncremap -s ${DATA}/grids/257x512_SCRIP.20150901.nc -g ${DATA}/grids/conusx4v1np4_chevrons_scrip_c150815.nc -m ${DATA}/maps/map_fv257x512_to_conusx4v1np4_chevrons_bilin.20150901.nc ncks -O -D 5 -v FSNT --map ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.150418.nc ${DATA}/ne30/raw/famipc5_ne30_v0.3_00003.cam.h0.1979-01.nc ${DATA}/ne30/rgr/fv_FSNT.nc ncks -O -D 5 -v FSNT --rgr diagnose_area --map ${DATA}/maps/map_fv257x512_to_conusx4v1np4_chevrons_bilin.20150901.nc ${DATA}/ne30/rgr/fv_FSNT.nc ${DATA}/ne30/rgr/dogfood.nc ncks -O -D 1 --rgr infer#diagnose_area --rgr grid=${HOME}/grd.nc ${DATA}/ne30/rgr/dogfood.nc ~/foo.nc ncks -H -s %20.15e, -v area -d ncol,0 ${DATA}/ne30/rgr/dogfood.nc ncks -H -s %20.15e, -v grid_area -d grid_size,0 ${DATA}/grids/conusx4v1np4_chevrons_scrip_c150815.nc ncks -H -s %20.15e, -v grid_area -d grid_size,0 ${HOME}/grd.nc ncol=0 on conus chevrons file: 3.653857995295246e-05 raw GLL weight 3.653857995294305e-05 ESMF weight (area_b from map-file) 3.653857995294302e-05 matlab CSZ decomposition (N-2 triangles) computed at SNL by MAT 3.653857995294301e-05 matlab centroidal decomposition (N triangles) computed at SNL by MAT 3.653857995294258e-05 NCO CSZ _and_ centroidal decompositions (new haversine) 3.653857995289623e-05 NCO CSZ decomposition (old acos) 20191011: Tested this same polygon in ESMF and NCO weight-generator NCO maps begin with first destination gridcell, find next ESMF gridcell by searching for first col: ncks --trd -C -v col ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc | egrep "=1 " ncks -H --trd -s %20.15e -C -d n_b,0 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc 3.653857995294305e-05 ncks -H --trd -s '%20.15e, ' -C -d n_b,0 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc 3.653857995295246e-05 ESMF and NCO weight-generators produce nearly identical S results to double-precision: ncks -H --trd -s '%20.15e, ' -C -d n_s,0,1 -v S ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc 2.181999640069480e-03, 1.309571213636605e-02 ncks -H --trd -s %20.15e -C -d n_s,207436 -d n_s,209617 -v S ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc 2.181999640069454e-03, 1.309571213636510e-02 Compare first five polygon areas: ncks --trd -H -C -s '%20.15e, ' -d n_b,0,4 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc ncks --trd -H -C -s '%20.15e, ' -d n_b,0,4 -v area_b ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc 3.653857995294305e-05, 1.250459284052488e-04, 1.448204605591709e-04, 8.223598867312266e-05, 8.585831933875070e-05, # aave 3.653857995294258e-05, 1.250459284052470e-04, 1.448204605591675e-04, 8.223598867312247e-05, 8.585831933875186e-05, Compare total areas: ncwa -O -y ttl -v area.? ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_aave.20191001.nc ~/foo_aave.nc ncwa -O -y ttl -v area.? ${DATA}/maps/map_cmip6_180x360_to_conusx4v1np4_chevrons_nco.20191001.nc ~/foo_nco.nc ncks --trd -H -C -s '%20.15e, ' -v area.? ~/foo_aave.nc ncks --trd -H -C -s '%20.15e, ' -v area.? ~/foo_nco.nc aave: 1.256637061435867e+01, 1.256637061435973e+01 nco: 1.256637061435857e+01, 1.256637061435955e+01 4*pi: 1.25663706143591729538e+01 Does (tru_glb_ttl/NCO_glb_ttl)*NCO_lcl = ESMF_lcl ? (1.25663706143591729538/1.256637061435857)*3.653857995294258=3.6538579952944333 No, normalization alone does not explain differences between ESMF and NCO It does not appear that ESMF does a global normalization of areas/weights */ /* Computing great circle arcs over small arcs requires care since central angle is near 0 degrees Cosine small angles changes slowly for such angles, and leads to precision loss Use haversine formula instead of spherical law of cosines formula https://en.wikipedia.org/wiki/Great-circle_distance */ /* Interior angle/great circle arc a, spherical law of cosines formula (loses precision): cos_a=lat_bnd_cos[idx_a]*lon_bnd_cos[idx_a]*lat_bnd_cos[idx_b]*lon_bnd_cos[idx_b]+ lat_bnd_cos[idx_a]*lon_bnd_sin[idx_a]*lat_bnd_cos[idx_b]*lon_bnd_sin[idx_b]+ lat_bnd_sin[idx_a]*lat_bnd_sin[idx_b];ngl_a=acos(cos_a); */ /* Interior angle/great circle arc a, haversine formula: */ // 20160918: Use branch cut rules for longitude lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_a],lon_bnd_rdn[idx_b])); lat_dlt=fabs(lat_bnd_rdn[idx_a]-lat_bnd_rdn[idx_b]); sin_hlf_tht=sqrt(pow(sin(0.5*lat_dlt),2)+lat_bnd_cos[idx_a]*lat_bnd_cos[idx_b]*pow(sin(0.5*lon_dlt),2)); ngl_a=2.0*asin(sin_hlf_tht); }else{ /* !tri_idx == 0 */ ngl_a=ngl_c; } /* !tri_idx == 0 */ /* Interior angle/great circle arc b */ lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_b],lon_bnd_rdn[idx_c])); lat_dlt=fabs(lat_bnd_rdn[idx_b]-lat_bnd_rdn[idx_c]); sin_hlf_tht=sqrt(pow(sin(0.5*lat_dlt),2)+lat_bnd_cos[idx_b]*lat_bnd_cos[idx_c]*pow(sin(0.5*lon_dlt),2)); ngl_b=2.0*asin(sin_hlf_tht); /* Interior angle/great circle arc c */ lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_c],lon_bnd_rdn[idx_a])); lat_dlt=fabs(lat_bnd_rdn[idx_c]-lat_bnd_rdn[idx_a]); sin_hlf_tht=sqrt(pow(sin(0.5*lat_dlt),2)+lat_bnd_cos[idx_c]*lat_bnd_cos[idx_a]*pow(sin(0.5*lon_dlt),2)); ngl_c=2.0*asin(sin_hlf_tht); /* Semi-perimeter */ prm_smi=0.5*(ngl_a+ngl_b+ngl_c); /* L'Huilier's formula results in NaN if any side exceeds semi-perimeter This can occur in needle-shaped triangles due to rounding errors in derived arc lengths a, b, c 20200203: Problematic needles occurs a few dozen times in ne120pg2 -> cmip6 maps Problematic isoceles triangles are much rarer than problematic needles Therefore look for needle-issues first, then, if none found, look for isoceles issues Wikipedia recommends treating ill-conditioned triangles by Side-Angle-Side (SAS) formula https://en.wikipedia.org/wiki/Spherical_trigonometry Diagnose needles beforehand and call SAS routines as above to avoid NaN in L'Huilier Label problematic needle triangles by shortest side, e.g., "flg_sas_a" means (b ~ c) and a ~ 0.0 */ flg_sas_ndl=flg_sas_isc=flg_sas_a=flg_sas_b=flg_sas_c=False; if(ngl_a > prm_smi){if(ngl_b > ngl_c) flg_sas_c=True; else flg_sas_b=True;} /* a exceeds semi-perimeter */ else if(ngl_b > prm_smi){if(ngl_c > ngl_a) flg_sas_a=True; else flg_sas_c=True;} /* b exceeds semi-perimeter */ else if(ngl_c > prm_smi){if(ngl_a > ngl_b) flg_sas_b=True; else flg_sas_a=True;} /* c exceeds semi-perimeter */ if(flg_sas_a || flg_sas_b || flg_sas_c) flg_sas_ndl=True; if(!flg_sas_ndl){ /* L'Huilier's formula becomes ill-conditioned when two sides are one half the third side This occurs for flat, isoceles-shaped triangles Label problematic isoceles triangles by longest side, e.g., "flg_sas_a" means (b ~ c) ~ 0.5*a */ /* Sensitivity tests on ~20191014 showed that triangular ill-conditioning treatment (i.e., switching to SAS method) does not improve (and may degrade) accuracy for eps_ill_cnd > 1.0e-15 */ const double eps_ill_cnd=1.0e-15; /* [frc] Ill-conditioned tolerance for interior angle/great circle arcs in triangle */ const double eps_ill_cnd_dbl=2.0*eps_ill_cnd; /* [frc] Ill-conditioned tolerance for interior angle/great circle arcs in triangle */ if((fabs(ngl_a-ngl_b) < eps_ill_cnd) && (fabs(ngl_a-0.5*ngl_c) < eps_ill_cnd_dbl)) flg_sas_c=True; /* c is twice a and b */ else if((fabs(ngl_b-ngl_c) < eps_ill_cnd) && (fabs(ngl_b-0.5*ngl_a) < eps_ill_cnd_dbl)) flg_sas_a=True; /* a is twice b and c */ else if((fabs(ngl_c-ngl_a) < eps_ill_cnd) && (fabs(ngl_c-0.5*ngl_b) < eps_ill_cnd_dbl)) flg_sas_b=True; /* b is twice c and a */ if(flg_sas_a || flg_sas_b || flg_sas_c) flg_sas_isc=True; } /* !flg_sas_ndl */ if(flg_sas_isc || flg_sas_ndl){ /* Compute area using SAS formula */ double cos_hlf_C; /* [frc] Cosine of half of canoncal surface angle C */ //double sin_hlf_C; /* [frc] Sine of half of canoncal surface angle C */ double ngl_sfc_ltr_C; /* [rdn] Canonical surface angle/great circle arc C */ double tan_hlf_a_tan_hlf_b; /* [frc] Product of tangents of one-half of nearly equal canoncal sides */ double xcs_sph_hlf_tan; /* [frc] Tangent of one-half the spherical excess */ /* Transform sides into canonical order for formula where C is surface angle between arcs a and b */ if(flg_sas_c){ ngl_ltr_a=ngl_a; ngl_ltr_b=ngl_b; ngl_ltr_c=ngl_c; } /* !flg_sas_c */ if(flg_sas_a){ ngl_ltr_a=ngl_b; ngl_ltr_b=ngl_c; ngl_ltr_c=ngl_a; } /* !flg_sas_a */ if(flg_sas_b){ ngl_ltr_a=ngl_c; ngl_ltr_b=ngl_a; ngl_ltr_c=ngl_b; } /* !flg_sas_b */ if(flg_sas_ndl && (nco_dbg_lvl_get() >= nco_dbg_scl)) (void)fprintf(stdout,"%s: INFO %s reports col_idx = %li triangle %d is needle-shaped triangle with a side that exceeds semi-perimeter = %0.16e. Eschew L'Huilier's formula for spherical excess to avoid NaN. Could use SAS formula with canonical central interior arc c = %0.16e.\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,prm_smi,ngl_ltr_c); if(flg_sas_isc && (nco_dbg_lvl_get() >= nco_dbg_scl)) (void)fprintf(stdout,"%s: INFO %s reports col_idx = %li triangle %d is nearly flat isoceles-shaped triangle. Canonical arcs a and b differ by %0.16e. Eschew L'Huilier's formula for spherical excess to avoid low precision. Could use SAS formula.\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,fabs(ngl_ltr_a-ngl_ltr_b)); /* Determine canonical surface angle C To find any angle given three spherical triangle sides, Wikipedia opines: "The cosine rule may be used to give the angles A, B, and C but, to avoid ambiguities, the half-angle formulae are preferred." Half-angle formulae include two applicable variants that yield the sine or cosine of half C Then C is determined as twice the asin() or acos() function, respectively For needle-shaped triangles, RHS sin formula is ~ sin^2(0)/sin(a)*sin(b) ~ 0.0 For needle-shaped triangles, RHS cos formula is ~ sin^2(s)/sin(a)*sin(b) ~ 0.5 For flat isoceles triangles, RHS sin formula is ~ sin^2(0)/sin(a)*sin(b) ~ 0.0 For flat isoceles triangles, RHS cos formula is ~ sin(s)*sin(0)/sin(a)*sin(b) ~ 0.0 Use sin formula since both needle- and isoceles-shaped triangles have RHS ~ 0.0 where arcsin() is most precise 20200203: Half-angle sine formula gives NaNs, and half-angle cosine formula works on ne120pg2->cmip. Why? Adopting cosine formula because it works */ //sin_hlf_C=sqrt(sin(prm_smi-ngl_ltr_a)*sin(prm_smi-ngl_ltr_b)/(sin(ngl_ltr_a)*sin(ngl_ltr_b))); // Half-angle sine formula cos_hlf_C=sqrt(sin(prm_smi)*sin(prm_smi-ngl_ltr_c)/(sin(ngl_ltr_a)*sin(ngl_ltr_b))); // Half-angle cosine formula //ngl_sfc_ltr_C=2.0*asin(sin_hlf_C); ngl_sfc_ltr_C=2.0*acos(cos_hlf_C); /* SAS formula */ tan_hlf_a_tan_hlf_b=tan(0.5*ngl_ltr_a)*tan(0.5*ngl_ltr_b); xcs_sph_hlf_tan=tan_hlf_a_tan_hlf_b*sin(ngl_sfc_ltr_C)/(1.0+tan_hlf_a_tan_hlf_b*cos(ngl_sfc_ltr_C)); assert(fabs(xcs_sph_hlf_tan) != M_PI_2); xcs_sph=2.0*atan(xcs_sph_hlf_tan); if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO SAS area formula for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16e, %0.16e, %0.16e). Spherical excess = %0.16e.\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c,xcs_sph); // Single-line version // xcs_sph=2.0*atan(tan(0.5*ngl_ltr_a)*tan(0.5*ngl_ltr_b)*sin(2.0*acos(sqrt(sin(prm_smi)*sin(prm_smi-ngl_c)/(sin(ngl_a)*sin(ngl_b)))))/(1.0+tan_hlf_a_tan_hlf_b*cos(2.0*acos(sqrt(sin(prm_smi)*sin(prm_smi-ngl_c)/(sin(ngl_a)*sin(ngl_b))))))); /* Above procedure for problematic needle-shaped and isoceles-shaped triangles degrades statistics For ne30pg2, ne120pg2 -> cmip, setting area = 0.0 _greatly_ improves area statistics (Why?) Set spherical excess to zero for problematic needle-shaped and isoceles-shaped triangles */ /* fxm: Make zeroing skinny needles/isoceles-shaped triangle-areas a command-line option? */ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO Setting SAS area = 0.0\n",nco_prg_nm_get()); xcs_sph=0.0; /* !flg_sas */ }else{ double xcs_sph_qtr_tan; /* [frc] Tangent of one-quarter the spherical excess */ xcs_sph_qtr_tan=sqrt(tan(0.5*prm_smi)*tan(0.5*(prm_smi-ngl_a))*tan(0.5*(prm_smi-ngl_b))*tan(0.5*(prm_smi-ngl_c))); assert(fabs(xcs_sph_qtr_tan) != M_PI_2); xcs_sph=4.0*atan(xcs_sph_qtr_tan); /* 20191014: Aggregate all previous area-related commands into one, gigantic, unreadable, possibly more precise command (tested and it is more obfuscated but not more precise) */ // xcs_sph=4.0*atan(sqrt(tan(0.5*0.5*(ngl_a+ngl_b+ngl_c))*tan(0.5*(0.5*(ngl_a+ngl_b+ngl_c)-ngl_a))*tan(0.5*(0.5*(ngl_a+ngl_b+ngl_c)-ngl_b))*tan(0.5*(0.5*(ngl_a+ngl_b+ngl_c)-ngl_c)))); } /* !flg_sas */ if(isnan(xcs_sph)){ const double eps_ngl_skn=1.0e-13; /* [frc] Angles skinnier than this form needles whose area ~ 0.0 */ /* Categorize reason for NaN */ (void)fprintf(stdout,"%s: WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\nUnxpected NaN polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16e, %0.16e, %0.16e).\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); if( /* Side exceeds semi-perimeter */ (ngl_a > prm_smi) || (ngl_b > prm_smi) || (ngl_c > prm_smi) ){ (void)fprintf(stdout,"%s: WARNING Triangle side exceeds semi-perimeter = %0.16e polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16e, %0.16e, %0.16e). Assigned triangle area = 0.0.\n",nco_prg_nm_get(),prm_smi,col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); }else if( /* Are angles too skinny? Quite often on ne30pg2, ne120pg2 */ (ngl_a < eps_ngl_skn) || (ngl_b < eps_ngl_skn) || (ngl_c < eps_ngl_skn) ){ (void)fprintf(stdout,"%s: WARNING Triangle has at least one skinny angles < %g [rdn] for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16f, %0.16f, %0.16f). Assigned triangle area = 0.0.\n",nco_prg_nm_get(),eps_ngl_skn,col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); }else if( /* Are two vertices identical to double-precision? Never on ne30pg2, ne120pg2 */ ((lat_bnd[idx_a] == lat_bnd[idx_b]) && (lon_bnd[idx_a] == lon_bnd[idx_b])) || ((lat_bnd[idx_b] == lat_bnd[idx_c]) && (lon_bnd[idx_b] == lon_bnd[idx_c])) || ((lat_bnd[idx_c] == lat_bnd[idx_a]) && (lon_bnd[idx_c] == lon_bnd[idx_a])) ){ (void)fprintf(stdout,"%s: WARNING Triangle has repeated points for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g). Assigned triangle area = 0.0.\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c]); }else{ (void)fprintf(stdout,"%s: WARNING Triangle area formula yields NaN for polygon col_idx = %li, triangle %d, vertices A, B, C at (lat,lon) [dgr] = (%0.16f, %0.16f), (%0.16f, %0.16f), (%0.16f, %0.16f). Interior angles/great circle arcs (a, b, c) [rdn] = (%0.16f, %0.16f, %0.16f). Are points co-linear? Assigned triangle area = 0.0.\n",nco_prg_nm_get(),col_idx,tri_idx,lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c],ngl_a,ngl_b,ngl_c); } /* !co-linear */ xcs_sph=0.0; } /* !NaN */ area[col_idx]+=xcs_sph; /* Accumulate spherical triangle area into reported polygon area and adjust below */ area_smc+=xcs_sph; /* Accumulate spherical triangle area into small-circle polygon area and adjust below */ area_ttl+=xcs_sph; /* Accumulate spherical triangle area into spherical polygon area */ area_smc_ttl+=xcs_sph; /* Accumulate spherical triangle area into total polygon area and adjust below */ /* 20160918 from here to end of loop is non-spherical work 20170217: Temporarily turn-off latitude circle diagnostics because Sungduk's POP case breaks them Canonical latitude-triangle geometry has point A at apex and points B and C at same latitude ncremap --dbg=1 --alg_typ=nco --grd_src=${DATA}/grids/ne30np4_pentagons.091226.nc --grd_dst=${DATA}/grids/cmip6_180x360_scrip.20181001.nc --map=${DATA}/maps/map_ne30np4_to_cmip6_180x360_nco.20190601.nc ncremap --dbg=1 -R 'edg_typ=smc' --alg_typ=nco --grd_src=${DATA}/grids/ne30np4_pentagons.091226.nc --grd_dst=${DATA}/grids/cmip6_180x360_scrip.20181001.nc --map=${DATA}/maps/map_ne30np4_to_cmip6_180x360_smc.20190601.nc */ flg_tri_crr_smc=False; if(lat_bnd_rdn[idx_a] == lat_bnd_rdn[idx_b] || lat_bnd_rdn[idx_b] == lat_bnd_rdn[idx_c] || lat_bnd_rdn[idx_c] == lat_bnd_rdn[idx_a]){ /* Set flag only if triangle is not degenerate. Degenerate triangles (3 points on a geodesic) have zero area */ if(xcs_sph != 0.0) flg_ply_has_smc=flg_tri_crr_smc=True; if(nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: DEBUG Found small circle triangle with vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c]); } /* endif */ if((edg_typ == nco_edg_smc) && flg_tri_crr_smc){ double ngl_plr; /* [rdn] Polar angle (co-latitude) */ long idx_ltr_a; /* [idx] Point A (apex) of canonical latitude-triangle geometry, 1-D index */ long idx_ltr_b; /* [idx] Point B (base) of canonical latitude-triangle geometry, 1-D index */ long idx_ltr_c; /* [idx] Point C (base) of canonical latitude-triangle geometry, 1-D index */ /* Rotate labels to standard position with vertex A, equi-latitude points B and C */ if(lat_bnd_rdn[idx_a] == lat_bnd_rdn[idx_b]){ idx_ltr_a=idx_c; idx_ltr_b=idx_a; idx_ltr_c=idx_b; ngl_ltr_a=ngl_c; ngl_ltr_b=ngl_a; ngl_ltr_c=ngl_b; ngl_plr=fabs(M_PI_2-lat_bnd_rdn[idx_a]); }else if(lat_bnd_rdn[idx_b] == lat_bnd_rdn[idx_c]){ idx_ltr_a=idx_a; idx_ltr_b=idx_b; idx_ltr_c=idx_c; ngl_ltr_a=ngl_a; ngl_ltr_b=ngl_b; ngl_ltr_c=ngl_c; ngl_plr=fabs(M_PI_2-lat_bnd_rdn[idx_b]); }else if(lat_bnd_rdn[idx_c] == lat_bnd_rdn[idx_a]){ idx_ltr_a=idx_b; idx_ltr_b=idx_c; idx_ltr_c=idx_a; ngl_ltr_a=ngl_b; ngl_ltr_b=ngl_c; ngl_ltr_c=ngl_a; ngl_plr=fabs(M_PI_2-lat_bnd_rdn[idx_c]); }else{ (void)fprintf(stdout,"%s: ERROR latitudes not equal in small circle section. Vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_a],lon_bnd[idx_a],lat_bnd[idx_b],lon_bnd[idx_b],lat_bnd[idx_c],lon_bnd[idx_c]); abort(); } /* endif */ /* 20160918: Compute exact area of latitude triangle wedge */ double xpn_x; /* [frc] Expansion parameter */ lon_dlt=fabs(nco_lon_dff_brnch_rdn(lon_bnd_rdn[idx_ltr_b],lon_bnd_rdn[idx_ltr_c])); assert(lon_dlt != 0.0); // Latitude triangles must have bases with distinct longitudes if(lon_dlt != M_PI){ /* Normal clause executed for small-circle triangles */ /* Numeric conditioning uncertain. Approaches divide-by-zero when lon_dlt << 1 */ xpn_x=lat_bnd_sin[idx_ltr_b]*(1.0-cos(lon_dlt))/sin(lon_dlt); assert(fabs(xpn_x) != M_PI_2); area_smc_crc=2.0*atan(xpn_x); /* 20170217: Sungduk's POP regrid triggers following abort(): ncremap -D 1 -i ~/pop_g16.nc -d ~/cam_f19.nc -o ~/foo.nc */ //assert(xpn_x >= 0.0); //if(lat_bnd[idx_ltr_b] > 0.0) area_smc_crc+=-lon_dlt*lat_bnd_sin[idx_ltr_b]; else area_smc_crc+=+lon_dlt*lat_bnd_sin[idx_ltr_b]; area_smc_crc+=-lon_dlt*lat_bnd_sin[idx_ltr_b]; }else{ /* 20200228: Latitude triangles may have bases with longitudes that differ by 180 degrees Consider a quadrilateral with four equidistant vertices in longitude, and that caps a pole: CSZ decomposition technique divides this into two triangles each with three co-latitudinal points and no vertex at pole Solution candidates: 1. Divide such quadrilaterals using centroid technique Just realized current implementation of centroid decomposition fails on polar caps Failure occurs because centroid latitude is +/- ~90 not mean of vertices' latitudes Must impute "pseudo-centroid" with latitude +/- 90 instead of averaging vertex latitudes Requires testing each polygon to determine if it contains pole <- Too difficult/expensive 2. Assume latitude triangles whose base is 180 degrees are at pole Compute area exactly using analytic formula for annular lune */ (void)fprintf(stdout,"%s: INFO longitudes differ by pi in small circle section. Vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_ltr_a],lon_bnd[idx_ltr_a],lat_bnd[idx_ltr_b],lon_bnd[idx_ltr_b],lat_bnd[idx_ltr_c],lon_bnd[idx_ltr_c]); (void)fprintf(stdout,"%s: DEBUG col_nbr=%lu, bnd_nbr=%d, col_idx=%ld, area=%g. Vertices [0..bnd_nbr-1] in format idx (lat,lon)\n",nco_prg_nm_get(),col_nbr,bnd_nbr,col_idx,xcs_sph); for(int bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%2d (%g, %g)\n",bnd_idx,lat_bnd[bnd_nbr*col_idx+bnd_idx],lon_bnd[bnd_nbr*col_idx+bnd_idx]); (void)fprintf(stdout,"%s: INFO Assuming this triangle is decomposed from polar cap polygon. Treating area with analytic formula for annular lune\n",nco_prg_nm_get()); /* Compute small circle correction as difference between spherical triangle area and standard annuular lune formula Small circle correction is positive-definite for polar triangles so use fabs(sin(lat_bnd_sin)) */ area_smc_crc=lon_dlt*fabs(lat_bnd_sin[idx_ltr_b])-area_smc; } /* !lon_dlt */ // Adjust diagnostic areas by small-circle area correction area_smc+=area_smc_crc; area_smc_ttl+=area_smc_crc; area_smc_crc_ttl+=area_smc_crc; area_smc_crc_abs_ttl+=fabs(area_smc_crc); // 20200109: Adjust area reported to calling code by small-circle area correction area[col_idx]+=area_smc_crc; if(0){ /* 20160918: Approximate area of latitude triangle wedge. Use truncated power expansion of exact formula. */ double xpn_x_sqr; /* [frc] Expansion parameter squared */ double xpn_sum; /* [frc] Expansion sum */ double xpn_nmr; /* [frc] Expansion term numerator */ double xpn_trm; /* [frc] Expansion term */ double xpn_dnm; /* [frc] Expansion term denominator */ const unsigned short int rdr_xpn=3; /* [nbr] Order of N in trigonometric series expansion */ unsigned short int idx_xpn; /* [idx] Index in series expansion */ xpn_x=cos(ngl_plr)*(1.0-cos(lon_dlt))/sin(lon_dlt); xpn_x_sqr=xpn_x*xpn_x; xpn_nmr=xpn_x; xpn_dnm=1.0; xpn_trm=xpn_nmr/xpn_dnm; xpn_sum+=xpn_trm; for(idx_xpn=3;idx_xpn<=rdr_xpn;idx_xpn+=2){ xpn_nmr*=xpn_x_sqr; xpn_dnm*=(idx_xpn-1)*idx_xpn; xpn_trm=xpn_nmr/xpn_dnm; xpn_sum+=xpn_trm; } /* !idx_xpn */ (void)fprintf(stdout,"%s: Small-circle area using series approximation...not implemented yet\n",nco_prg_nm_get()); } /* !0 */ if(nco_dbg_lvl_get() >= nco_dbg_scl){ (void)fprintf(stdout,"%s: INFO %s col_idx = %li triangle %d spherical area, latitude-triangle area, %% difference: %g, %g, %g%%\n",nco_prg_nm_get(),fnc_nm,col_idx,tri_idx,xcs_sph,xcs_sph+area_smc_crc,100.0*area_smc_crc/xcs_sph); if(fabs(area_smc_crc/xcs_sph) > 0.1){ (void)fprintf(stdout,"%s: DEBUG Non-spherical correction exceeds 10%% for current triangle with vertices A, B, C at (lat,lon) [dgr] = (%g, %g), (%g, %g), (%g, %g)\n",nco_prg_nm_get(),lat_bnd[idx_ltr_a],lon_bnd[idx_ltr_a],lat_bnd[idx_ltr_b],lon_bnd[idx_ltr_b],lat_bnd[idx_ltr_c],lon_bnd[idx_ltr_c]); } /* !fabs */ } /* !dbg */ } /* !edg_typ && flg_tri_crr_smc */ } /* !tri_idx */ if(edg_typ == nco_edg_smc && flg_ply_has_smc){ /* Current gridcell contained at least one latitude-triangle */ if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO %s col_idx = %li spherical area, small circle area, %% difference: %g, %g, %g%%\n",nco_prg_nm_get(),fnc_nm,col_idx,area[col_idx],area_smc,100.0*(area_smc-area[col_idx])/area[col_idx]); } /* !edg_typ && !flg_ply_has_smc */ } /* !col_idx */ if(edg_typ == nco_edg_smc && nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: INFO %s total spherical area, small circle area, %% difference, crc_ttl, crc_abs_ttl: %g, %g, %g%%, %g, %g\n",nco_prg_nm_get(),fnc_nm,area_ttl,area_smc_ttl,100.0*(area_smc_ttl-area_ttl)/area_ttl,area_smc_crc_ttl,area_smc_crc_abs_ttl); if(vrt_vld) vrt_vld=(long *)nco_free(vrt_vld); if(a_idx) a_idx=(long *)nco_free(a_idx); if(b_idx) b_idx=(long *)nco_free(b_idx); if(c_idx) c_idx=(long *)nco_free(c_idx); if(lat_bnd_rdn) lat_bnd_rdn=(double *)nco_free(lat_bnd_rdn); if(lon_bnd_rdn) lon_bnd_rdn=(double *)nco_free(lon_bnd_rdn); if(lat_bnd_cos) lat_bnd_cos=(double *)nco_free(lat_bnd_cos); if(lon_bnd_cos) lon_bnd_cos=(double *)nco_free(lon_bnd_cos); if(lat_bnd_sin) lat_bnd_sin=(double *)nco_free(lat_bnd_sin); if(lon_bnd_sin) lon_bnd_sin=(double *)nco_free(lon_bnd_sin); } /* !nco_sph_plg_area() */ int /* O [enm] Return code */ nco_rgr_tps /* [fnc] Regrid using TempestRemap library */ (rgr_sct * const rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Regrid fields using TempestRemap "library" (more precisely, executables) Routine was originally written to call Tempest executables However, that functionality was all placed into the ncremap shell script Thus this C-interface is currently unused TempestRemap2 has a library that may be accessed on-line Test Tempest library: no way to activate yet export DATA_TEMPEST='/data/zender/rgr';ncks -O --rgr=Y ${DATA}/rgr/essgcm14_clm.nc ~/foo.nc */ const char fnc_nm[]="nco_rgr_tps()"; const int fmt_chr_nbr=6; const char *cmd_rgr_fmt; char *cmd_rgr; char fl_grd_dst[]="/tmp/foo_outRLLMesh.g"; char *fl_grd_dst_cdl; int rcd_sys; int lat_nbr_rqs=180; int lon_nbr_rqs=360; nco_rgr_tps_cmd nco_tps_cmd; /* [enm] TempestRemap command enum */ char *nvr_DATA_TEMPEST; /* [sng] Directory where Tempest grids, meshes, and weights are stored */ nvr_DATA_TEMPEST=getenv("DATA_TEMPEST"); rgr->drc_tps= (nvr_DATA_TEMPEST && strlen(nvr_DATA_TEMPEST) > 0L) ? (char *)strdup(nvr_DATA_TEMPEST) : (char *)strdup("/tmp"); if(nco_dbg_lvl_get() >= nco_dbg_crr){ (void)fprintf(stderr,"%s: INFO %s reports\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stderr,"drc_tps = %s, ",rgr->drc_tps ? rgr->drc_tps : "NULL"); (void)fprintf(stderr,"\n"); } /* endif dbg */ /* Allow for whitespace characters in fl_grd_dst Assume CDL translation results in acceptable name for shell commands */ fl_grd_dst_cdl=nm2sng_fl(fl_grd_dst); /* Construct and execute regridding command */ nco_tps_cmd=nco_rgr_GenerateRLLMesh; cmd_rgr_fmt=nco_tps_cmd_fmt_sng(nco_tps_cmd); cmd_rgr=(char *)nco_malloc((strlen(cmd_rgr_fmt)+strlen(fl_grd_dst_cdl)-fmt_chr_nbr+1UL)*sizeof(char)); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stderr,"%s: %s reports generating %d by %d RLL mesh in %s...\n",nco_prg_nm_get(),fnc_nm,lat_nbr_rqs,lon_nbr_rqs,fl_grd_dst); (void)sprintf(cmd_rgr,cmd_rgr_fmt,lat_nbr_rqs,lon_nbr_rqs,fl_grd_dst_cdl); rcd_sys=system(cmd_rgr); if(rcd_sys == -1){ (void)fprintf(stdout,"%s: ERROR %s unable to complete TempestRemap regridding command \"%s\"\n",nco_prg_nm_get(),fnc_nm,cmd_rgr); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"done\n"); /* Clean-up memory */ if(fl_grd_dst_cdl) fl_grd_dst_cdl=(char *)nco_free(fl_grd_dst_cdl); if(cmd_rgr) cmd_rgr=(char *)nco_free(cmd_rgr); return NCO_NOERR; } /* end nco_rgr_tps() */ const char * /* O [sng] String describing two-dimensional grid-type */ nco_grd_2D_sng /* [fnc] Convert two-dimensional grid-type enum to string */ (const nco_grd_2D_typ_enm nco_grd_2D_typ) /* I [enm] Two-dimensional grid-type enum */ { /* Purpose: Convert two-dimensional grid-type enum to string */ switch(nco_grd_2D_typ){ case nco_grd_2D_unk: return "Unknown, unclassified, or unrepresentable 2D grid type (e.g., unstructured, curvilinear, POP displaced-pole)"; case nco_grd_2D_gss: return "Gaussian latitude grid. Used by spectral transform models, e.g., CCM 1-3, CAM 1-3, ECMWF Forecast, LSM, MATCH, NCEP (R1, R2), UCICTM."; case nco_grd_2D_fv: return "Cap-latitude grid, aka FV-scalar grid (in Lin-Rood representation). When global (not regional) in extent and with odd number of latitudes, poles are considered at (and labeled as) centers of first and last gridcells. For example lat_ctr=-90,-89,-88,... and lat_crn=-89.5,-88.5,-87.5,... Thus pole-gridcells span half the equi-angular latitude increment of the rest of the grid. Used by CAM FV (i.e., CAM 4-6), ECMWF (ERA-I, ERA40, ERA5), GEOS-CHEM, UCICTM, UKMO."; case nco_grd_2D_eqa: return "Uniform/Equi-Angular latitude grid. Uniform/Equi-angle (everywhere) latitude grid. When global (not regional) in extent and with even number of latitudes, poles are at corners/edges of first and last gridcells. For example lat_ctr=-89.5,-88.5,-87.5,... and lat_crn=-90,-89,-88,.... When global, forms valid FV-staggered (aka FV-velocity, aka offset) grid (for Lin-Rood representation). Used by CIESIN/SEDAC, IGBP-DIS, NASA CMG, TOMS AAI, WOCE."; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_2D_sng() */ const char * /* O [sng] String describing latitude grid-type */ nco_grd_lat_sng /* [fnc] Convert latitude grid-type enum to string */ (const nco_grd_lat_typ_enm nco_grd_lat_typ) /* I [enm] Latitude grid-type enum */ { /* Purpose: Convert latitude grid-type enum to string */ switch(nco_grd_lat_typ){ case nco_grd_lat_unk: return "Unknown, unclassified, or unrepresentable latitude grid type (e.g., unstructured, curvilinear, POP3)"; case nco_grd_lat_gss: return "Gaussian latitude grid used by global spectral models: CCM 1-3, CAM 1-3, ECMWF Forecast, LSM, MATCH, NCEP (R1, R2), UCICTM."; case nco_grd_lat_fv: return "Cap-latitude grid, aka FV-scalar grid (in Lin-Rood representation). When global (not regional) in extent and with odd number of latitudes, poles are considered at (and labeled as) centers of first and last gridcells. For example lat_ctr=-90,-89,-88,... and lat_crn=-89.5,-88.5,-87.5,... Thus pole-gridcells span half the equi-angular latitude increment of the rest of the grid. Used by CAM FV (i.e., CAM 4-6), ECMWF (ERA-I, ERA40, ERA5), GEOS-CHEM, UCICTM, UKMO."; case nco_grd_lat_eqa: return "Uniform/Equi-Angular latitude grid. Uniform/Equi-angle (everywhere) latitude grid. When global (not regional) in extent and with even number of latitudes, poles are at corners/edges of first and last gridcells. For example lat_ctr=-89.5,-88.5,-87.5,... and lat_crn=-90,-89,-88,.... When global, forms valid FV-staggered (aka FV-velocity, aka offset) grid (for Lin-Rood representation). Used by CIESIN/SEDAC, IGBP-DIS, NASA CMG, TOMS AAI, WOCE."; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_lat_sng() */ const char * /* O [sng] String describing longitude grid-type */ nco_grd_lon_sng /* [fnc] Convert longitude grid-type enum to string */ (const nco_grd_lon_typ_enm nco_grd_lon_typ) /* I [enm] Longitude grid-type enum */ { /* Purpose: Convert longitude grid-type enum to string */ switch(nco_grd_lon_typ){ case nco_grd_lon_unk: return "Unknown, unclassified, or unrepresentable longitude grid type (e.g., unstructured, curvilinear)"; case nco_grd_lon_180_wst: return "Date line at west edge of first longitude cell"; case nco_grd_lon_180_ctr: return "Date line at center of first longitude cell"; case nco_grd_lon_Grn_wst: return "Greenwich at west edge of first longitude cell"; case nco_grd_lon_Grn_ctr: return "Greenwich at center of first longitude cell"; case nco_grd_lon_bb: return "Longitude grid determined by bounding box (lon_wst/lon_est) and gridcell number (lon_nbr)"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_lon_sng() */ const char * /* O [sng] String describing grid extent */ nco_grd_xtn_sng /* [fnc] Convert two-dimensional grid-extent enum to string */ (const nco_grd_xtn_enm nco_grd_xtn) /* I [enm] Grid-extent enum */ { /* Purpose: Convert grid-extent enum to string */ switch(nco_grd_xtn){ case nco_grd_xtn_nil: return "Unknown"; case nco_grd_xtn_glb: return "Global"; case nco_grd_xtn_rgn: return "Regional"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_grd_xtn_sng() */ const char * /* O [sng] String describing grid conversion */ nco_rgr_grd_sng /* [fnc] Convert grid conversion enum to string */ (const nco_rgr_typ_enm nco_rgr_typ) /* I [enm] Grid conversion enum */ { /* Purpose: Convert grid conversion enum to string */ switch(nco_rgr_typ){ case nco_rgr_grd_1D_to_1D: return "1D_to_1D"; case nco_rgr_grd_1D_to_2D: return "1D_to_2D"; case nco_rgr_grd_2D_to_1D: return "2D_to_1D"; case nco_rgr_grd_2D_to_2D: return "2D_to_2D"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_grd_sng() */ const char * /* O [sng] String describing regridding method */ nco_rgr_mth_sng /* [fnc] Convert regridding method enum to string */ (const nco_rgr_mth_typ_enm nco_rgr_mth_typ) /* I [enm] Regridding method enum */ { /* Purpose: Convert regridding method enum to string */ switch(nco_rgr_mth_typ){ case nco_rgr_mth_conservative: return "Conservative remapping"; case nco_rgr_mth_bilinear: return "Bilinear remapping"; case nco_rgr_mth_none: return "none"; case nco_rgr_mth_unknown: return "Unknown (TempestRemap or ESMF_weight_only)"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_mth_sng() */ const char * /* O [sng] String describing mapfile generator */ nco_rgr_mpf_sng /* [fnc] Convert mapfile generator enum to string */ (const nco_rgr_mpf_typ_enm nco_rgr_mpf_typ) /* I [enm] Mapfile generator enum */ { /* Purpose: Convert mapfile generator enum to string */ switch(nco_rgr_mpf_typ){ case nco_rgr_mpf_ESMF: return "ESMF Offline Regridding Weight Generator (ERWG), either from ESMF_RegridWeightGen directly or via NCL"; case nco_rgr_mpf_SCRIP: return "SCRIP (original LANL package)"; case nco_rgr_mpf_Tempest: return "TempestRemap (GenerateOfflineMap)"; case nco_rgr_mpf_ESMF_weight_only: return "ESMF Offline Regridding Weight Generator (ERWG), either from ESMF_RegridWeightGen directly or via NCL, with --weight_only option from ERWG 7.1+"; case nco_rgr_mpf_NCO: return "netCDF Operators (NCO) Offline Regridding Weight Generator"; case nco_rgr_mpf_MBTR: return "MOAB-TempestRemap Online Regridding Weight Generator"; case nco_rgr_mpf_unknown: return "Unknown Weight Generator"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_mpf_sng() */ const char * /* O [sng] String describing regridding normalization */ nco_rgr_nrm_sng /* [fnc] Convert regridding normalization enum to string */ (const nco_rgr_nrm_typ_enm nco_rgr_nrm_typ) /* I [enm] Regridding normalization enum */ { /* Purpose: Convert regridding normalization enum to string */ switch(nco_rgr_nrm_typ){ case nco_rgr_nrm_fracarea: return "fracarea"; case nco_rgr_nrm_destarea: return "destarea"; case nco_rgr_nrm_none: return "none"; case nco_rgr_nrm_unknown: return "Unknown (possibilities include ESMF_weight_only, NCO, and TempestRemap)"; default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_rgr_nrm_sng() */ const char * /* O [sng] String containing regridding command and format */ nco_tps_cmd_fmt_sng /* [fnc] Convert TempestRemap command enum to command string */ (const nco_rgr_tps_cmd nco_tps_cmd) /* I [enm] TempestRemap command enum */ { /* Purpose: Convert TempestRemap command enum to command string and format */ switch(nco_tps_cmd){ case nco_rgr_ApplyOfflineMap: return "ApplyOfflineMap"; case nco_rgr_CalculateDiffNorms: return "CalculateDiffNorms"; case nco_rgr_GenerateCSMesh: return "GenerateCSMesh --res %d --file %s"; case nco_rgr_GenerateGLLMetaData: return "GenerateGLLMetaData"; case nco_rgr_GenerateICOMesh: return "GenerateICOMesh"; case nco_rgr_GenerateLambertConfConicMesh: return "GenerateLambertConfConicMesh"; case nco_rgr_GenerateOfflineMap: return "GenerateOfflineMap --in_mesh %s --out_mesh %s --ov_mesh %s --in_data %s --out_data %s"; case nco_rgr_GenerateOverlapMesh: return "GenerateOverlapMesh --a %s --b %s --out %s"; case nco_rgr_GenerateRLLMesh: return "GenerateRLLMesh --lat %d --lon %d --file %s"; case nco_rgr_GenerateTestData: return "GenerateTestData --mesh %s --np %d --test %d --out %s"; case nco_rgr_MeshToTxt: return "MeshToTxt"; case nco_rgr_AAA_nil: case nco_rgr_ZZZ_last: default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_tps_cmd_fmt_sng() */ const char * /* O [sng] String containing regridding command name */ nco_tps_cmd_sng /* [fnc] Convert TempestRemap command enum to command name */ (const nco_rgr_tps_cmd nco_tps_cmd) /* I [enm] TempestRemap command enum */ { /* Purpose: Convert TempestRemap command enum to command string */ switch(nco_tps_cmd){ case nco_rgr_ApplyOfflineMap: return "ApplyOfflineMap"; case nco_rgr_CalculateDiffNorms: return "CalculateDiffNorms"; case nco_rgr_GenerateCSMesh: return "GenerateCSMesh"; case nco_rgr_GenerateGLLMetaData: return "GenerateGLLMetaData"; case nco_rgr_GenerateICOMesh: return "GenerateICOMesh"; case nco_rgr_GenerateLambertConfConicMesh: return "GenerateLambertConfConicMesh"; case nco_rgr_GenerateOfflineMap: return "GenerateOfflineMap"; case nco_rgr_GenerateOverlapMesh: return "GenerateOverlapMesh"; case nco_rgr_GenerateRLLMesh: return "GenerateRLLMesh"; case nco_rgr_GenerateTestData: return "GenerateTestData"; case nco_rgr_MeshToTxt: return "MeshToTxt"; case nco_rgr_AAA_nil: case nco_rgr_ZZZ_last: default: nco_dfl_case_generic_err(); break; } /* end switch */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* end nco_tps_cmd_sng() */ int /* O [enm] Return code */ nco_grd_mk /* [fnc] Create SCRIP-format grid file */ (rgr_sct * const rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Use grid information to create SCRIP-format grid file Spherical geometry terminology: spherical cap = spherical dome = volume cut-off by plane spherical lune = digon = area bounded by two half-great circles = base of spherical wedge spherical segment = volume defined by cutting sphere with pair parallel planes spherical sector = volume subtended by lat1 spherical wedge = ungula = volume subtended by lon2-lon1 spherical zone = area of spherical segment excluding bases spherical quadrangle = area of intersection of spherical zone and lune (i.e., area of bearing = angle from true north geodesic = shortest path between points on a surface great circle = orthodrome = "straight path" = geodesic of the sphere convergency = difference (in azimuth?) between great circle tracks at two different positions conversion angle = angle between geodesic and rhumb line rhumb line = loxodrome = "oblique (or slanted) path" = line of constant azimuth Formulae: http://www.movable-type.co.uk/scripts/latlong.html # On-line Javascript implementation http://williams.best.vwh.net/avform.htm ACME: https://acme-svn2.ornl.gov/acme-repo/acme/mapping/grids https://acme-svn2.ornl.gov/acme-repo/acme/inputdata/cpl/gridmaps NCAR: yellowstone.ucar.edu:/glade/p/cesm/cseg/mapping/grids yellowstone.ucar.edu:/glade/p_old/cesm/cseg/mapping/grids Global RLL grids: ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr grid=${DATA}/grids/180x360_SCRIP.20150901.nc --rgr latlon=180,360 --rgr lat_typ=eqa --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Equiangular grid 90x180' --rgr grid=${DATA}/grids/90x180_SCRIP.20150901.nc --rgr latlon=90,180 --rgr lat_typ=eqa --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc Maps for global RLL grids: ESMF_RegridWeightGen -s ${DATA}/grids/180x360_SCRIP.20150901.nc -d ${DATA}/grids/90x180_SCRIP.20150901.nc -w ${DATA}/maps/map_180x360_to_90x180.20150901.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/90x180_SCRIP.20150901.nc -d ${DATA}/grids/180x360_SCRIP.20150901.nc -w ${DATA}/maps/map_90x180_to_180x360.20150901.nc --method conserve ACME grids: ncks -O -D 1 --rgr ttl='FV-scalar grid 129x256' --rgr grid=${DATA}/grids/129x256_SCRIP.20150910.nc --rgr latlon=129,256 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='FV-scalar grid 257x512' --rgr grid=${DATA}/grids/257x512_SCRIP.20150910.nc --rgr latlon=257,512 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='FV-scalar grid 801x1600' --rgr grid=${DATA}/grids/801x1600_SCRIP.20150910.nc --rgr latlon=801,1600 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ACME maps: ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/129x256_SCRIP.20150910.nc -w ${DATA}/maps/map_ne30np4_to_fv129x256_aave.20150910.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/257x512_SCRIP.20150910.nc -w ${DATA}/maps/map_ne30np4_to_fv257x512_bilin.20150910.nc --method bilinear ESMF_RegridWeightGen -s ${DATA}/grids/ne120np4_pentagons.100310.nc -d ${DATA}/grids/257x512_SCRIP.20150910.nc -w ${DATA}/maps/map_ne120np4_to_fv257x512_aave.20150910.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne120np4_pentagons.100310.nc -d ${DATA}/grids/801x1600_SCRIP.20150910.nc -w ${DATA}/maps/map_ne120np4_to_fv801x1600_bilin.20150910.nc --method bilinear AMWG grids: AMWG diagnostics (until ~2016) mis-diagnose FV grids with odd numbers of latitudes as Gaussian Grids ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 96x144 for horizontal resolution 1.9x2.5 degrees' --rgr grid=${DATA}/grids/96x144_SCRIP.20160301.nc --rgr latlon=96,144 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 192x288 for horizontal resolution 0.9x1.25 degrees' --rgr grid=${DATA}/grids/192x288_SCRIP.20160301.nc --rgr latlon=192,288 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 128x256 for horizontal resolution 1.4x1.4 degrees' --rgr grid=${DATA}/grids/128x256_SCRIP.20160301.nc --rgr latlon=128,256 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 256x512 for horizontal resolution 0.7x0.7 degrees' --rgr grid=${DATA}/grids/256x512_SCRIP.20160301.nc --rgr latlon=256,512 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='CAM FV-scalar grid 800x1600 for horizontal resolution 0.225x0.225 degrees' --rgr grid=${DATA}/grids/800x1600_SCRIP.20160301.nc --rgr latlon=800,1600 --rgr lat_typ=cap --rgr lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Equiangular grid 360x720 produced by RTM' --rgr grid=${DATA}/grids/360x720rtm_SCRIP.20160301.nc --rgr latlon=360,720 --rgr lat_typ=eqa --rgr lon_typ=180_wst ~/nco/data/in.nc ~/foo.nc AMWG maps old method (no provenance archived): ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/128x256_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv128x256_aave.20160301.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/256x512_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv256x512_bilin.20160301.nc --method bilinear ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/256x512_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv256x512_aave.20160301.nc --method conserve ESMF_RegridWeightGen -s ${DATA}/grids/ne30np4_pentagons.091226.nc -d ${DATA}/grids/800x1600_SCRIP.20160301.nc -w ${DATA}/maps/map_ne30np4_to_fv800x1600_bilin.20160301.nc --method bilinear AMWG maps with ncremap (preferred method): ncremap -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/128x256_SCRIP.20160301.nc -m ${DATA}/maps/map_ne30np4_to_fv128x256_aave.20160301.nc -w esmf -a conserve ncremap -s ${DATA}/grids/ne30np4_pentagons.091226.nc -g ${DATA}/grids/256x512_SCRIP.20160301.nc -m ${DATA}/maps/map_ne30np4_to_fv256x512_bilin.20160301.nc -w esmf -a bilinear ncremap -s ${DATA}/grids/ne120np4_pentagons.100310.nc -g ${DATA}/grids/256x512_SCRIP.20160301.nc -m ${DATA}/maps/map_ne120np4_to_fv256x512_aave.20160301.nc -w esmf -a conserve ncremap -s ${DATA}/grids/ne120np4_pentagons.100310.nc -g ${DATA}/grids/800x1600_SCRIP.20160301.nc -m ${DATA}/maps/map_ne120np4_to_fv800x1600_bilin.20160301.nc -w esmf -a bilinear MPAS grids: NCO cannot yet generate MPAS grids, but given an MPAS grid it can generate appropriate maps MPAS maps: ncremap -s ${DATA}/grids/oEC60to30.SCRIP.150729.nc -g ${DATA}/grids/t62_SCRIP.20150901.nc -m ${DATA}/maps/map_oEC60to30_to_t62_aave.20160301.nc -w esmf -a conserve ncremap -s ${DATA}/grids/oEC60to30.SCRIP.150729.nc -g ${DATA}/grids/t62_SCRIP.20150901.nc -m ${DATA}/maps/map_oEC60to30_to_t62_bilin.20160301.nc -w esmf -a bilinear Regional RLL grids: ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr grid=${DATA}/sld/rgr/grd_dst.nc --rgr latlon=100,100 --rgr snwe=30.0,70.0,-120.0,-90.0 ~/nco/data/in.nc ~/foo.nc Global RLL skeleton: ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr skl=${DATA}/sld/rgr/skl_180x360.nc --rgr grid=${DATA}/grids/180x360_SCRIP.20150901.nc --rgr latlon=180,360#lat_typ=eqa#lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc Curvilinear grids: ncks -O -D 1 --rgr ttl='Curvilinear grid 10x20. Degenerate case.' --rgr crv --rgr lon_crv=0.0 --rgr skl=${DATA}/sld/rgr/skl_crv.nc --rgr grid=${DATA}/sld/rgr/grd_crv.nc --rgr latlon=10,20 --rgr snwe=-5.0,5.0,-10.0,10.0 ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Curvilinear grid 10x20. Curvilinearity = 1.0 lon' --rgr lon_crv=1.0 --rgr skl=${DATA}/sld/rgr/skl_crv.nc --rgr grid=${DATA}/sld/rgr/grd_crv.nc --rgr latlon=10,20 --rgr snwe=-5.0,5.0,-10.0,10.0 ~/nco/data/in.nc ~/foo.nc 1-D Latitude (no longitude) grids: ncks -O -D 1 --rgr ttl='Latitude-only zonal grid' --rgr skl=${DATA}/sld/rgr/skl_lat_10dgr_uni.nc --rgr grid=${DATA}/sld/rgr/grd_lat_10dgr_uni.nc --rgr latlon=18,1 --rgr snwe=-90,90,0,360 ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr ttl='Latitude-only zonal grid' --rgr skl=${DATA}/sld/rgr/skl_lat_05dgr_cap.nc --rgr grid=${DATA}/sld/rgr/grd_lat_05dgr_cap.nc --rgr latlon=37,1 --rgr snwe=-90,90,0,360 ~/nco/data/in.nc ~/foo.nc ncremap -i ${DATA}/sld/rgr/skl_lat_10dgr_uni.nc -d ${DATA}/sld/rgr/skl_lat_05dgr_cap.nc -m ${DATA}/maps/map_lat10uni_to_lat05cap_aave.nc -o ~/rgr/lat10to05.nc ESMF_RegridWeightGen -s ${DATA}/sld/rgr/grd_lat_10dgr_uni.nc -d ${DATA}/sld/rgr/grd_lat_05dgr_cap.nc -w ${DATA}/maps/map_lat10uni_to_lat05cap_aave.nc --method conserve */ const char fnc_nm[]="nco_grd_mk()"; /* [sng] Function name */ const double rdn2dgr=180.0/M_PI; const double dgr2rdn=M_PI/180.0; const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ const int dmn_nbr_3D=3; /* [nbr] Rank of 3-D grid variables */ const int dmn_nbr_grd_max=dmn_nbr_3D; /* [nbr] Maximum rank of grid variables */ const int itr_nbr_max=20; // [nbr] Maximum number of iterations const nc_type crd_typ=NC_DOUBLE; char *fl_out_tmp=NULL_CEWI; char *fl_out; char grd_area_nm[]="grid_area"; /* 20150830: NB ESMF_RegridWeightGen --user_areas looks for variable named "grid_area" */ char dmn_sz_nm[]="grid_dims"; char grd_crn_lat_nm[]="grid_corner_lat"; char grd_crn_lon_nm[]="grid_corner_lon"; char grd_crn_nm[]="grid_corners"; char grd_ctr_lat_nm[]="grid_center_lat"; char grd_ctr_lon_nm[]="grid_center_lon"; char grd_rnk_nm[]="grid_rank"; char grd_sz_nm[]="grid_size"; char msk_nm[]="grid_imask"; double *grd_ctr_lat; /* [dgr] Latitude centers of grid */ double *grd_ctr_lon; /* [dgr] Longitude centers of grid */ double *grd_crn_lat; /* [dgr] Latitude corners of grid */ double *grd_crn_lon; /* [dgr] Longitude corners of grid */ double *area; /* [sr] Area of grid */ double *lat_bnd=NULL_CEWI; /* [dgr] Latitude boundaries of rectangular grid */ double *lat_crn=NULL; /* [dgr] Latitude corners of rectangular grid */ double *lat_ctr=NULL_CEWI; /* [dgr] Latitude centers of rectangular grid */ double *lat_ntf=NULL; /* [dgr] Latitude interfaces of rectangular grid */ double *lat_wgt=NULL; /* [dgr] Latitude weights of rectangular grid */ double *lon_bnd=NULL_CEWI; /* [dgr] Longitude boundaries of rectangular grid */ double *lon_crn=NULL; /* [dgr] Longitude corners of rectangular grid */ double *lon_ctr=NULL_CEWI; /* [dgr] Longitude centers of rectangular grid */ double *lon_ntf=NULL; /* [dgr] Longitude interfaces of rectangular grid */ double area_ttl=0.0; /* [frc] Exact sum of area */ double lat_crv; /* [dgr] Latitudinal curvilinearity */ double lon_crv; /* [dgr] Longitudinal curvilinearity */ double lat_nrt; /* [dgr] Latitude of northern edge of grid */ double lat_sth; /* [dgr] Latitude of southern edge of grid */ double lat_wgt_ttl=0.0; /* [frc] Actual sum of quadrature weights */ double lat_wgt_gss; /* [frc] Latitude weight estimated from interface latitudes */ double lon_est; /* [dgr] Longitude of eastern edge of grid */ double lon_wst; /* [dgr] Longitude of western edge of grid */ double lon_ncr; /* [dgr] Longitude increment */ double lat_ncr; /* [dgr] Latitude increment */ double lon_spn; /* [dgr] Longitude span */ double lat_spn; /* [dgr] Latitude span */ double *wgt_Gss=NULL; // [frc] Gaussian weights double precision int *msk=NULL; /* [flg] Mask of grid */ int *dmn_sz_int; /* [nbr] Array of dimension sizes of grid */ int dmn_ids[dmn_nbr_grd_max]; /* [id] Dimension IDs array for output variable */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NC_FORMAT_CLASSIC; /* [enm] Output file format */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int area_id; /* [id] Area variable ID */ int dmn_id_grd_crn; /* [id] Grid corners dimension ID */ int dmn_id_grd_rnk; /* [id] Grid rank dimension ID */ int dmn_id_grd_sz; /* [id] Grid size dimension ID */ int dmn_sz_int_id; /* [id] Grid dimension sizes ID */ int grd_crn_lat_id; /* [id] Grid corner latitudes variable ID */ int grd_crn_lon_id; /* [id] Grid corner longitudes variable ID */ int grd_ctr_lat_id; /* [id] Grid center latitudes variable ID */ int grd_ctr_lon_id; /* [id] Grid center longitudes variable ID */ int itr_cnt; /* Iteration counter */ int msk_id; /* [id] Mask variable ID */ long dmn_srt[dmn_nbr_grd_max]; long dmn_cnt[dmn_nbr_grd_max]; long bnd_nbr; /* [nbr] Number of bounds in gridcell */ long col_nbr; /* [nbr] Number of columns in grid */ long crn_idx; /* [idx] Counting index for corners */ long grd_crn_nbr; /* [nbr] Number of corners in gridcell */ long grd_rnk_nbr; /* [nbr] Number of dimensions in grid */ long grd_sz_nbr; /* [nbr] Number of gridcells in grid */ long idx2; /* [idx] Counting index for unrolled grids */ long idx; /* [idx] Counting index for unrolled grids */ long lat_idx2; /* [idx] Counting index for unrolled latitude */ long lat_idx; long lat_nbr; /* [nbr] Number of latitudes in grid */ long lon_idx2; /* [idx] Counting index for unrolled longitude */ long lon_idx; long lon_nbr; /* [nbr] Number of longitudes in grid */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=True; /* Option O */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=rgr->flg_uio; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool WRT_TMP_FL=False; /* [flg] Write output to temporary file */ nco_bool flg_grd_1D=False; nco_bool flg_grd_2D=False; nco_bool flg_grd_crv=False; nco_bool flg_s2n=True; /* I [enm] Latitude grid-direction is South-to-North */ nco_grd_2D_typ_enm grd_typ; /* [enm] Grid-type enum */ nco_grd_lat_drc_enm lat_drc; /* [enm] Latitude grid-direction enum */ nco_grd_lat_typ_enm lat_typ; /* [enm] Latitude grid-type enum */ nco_grd_lon_typ_enm lon_typ; /* [enm] Longitude grid-type enum */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ dfl_lvl=rgr->dfl_lvl; grd_typ=rgr->grd_typ; /* [enm] Grid type */ fl_out=rgr->fl_grd; fl_out_fmt=rgr->fl_out_fmt; lat_drc=rgr->lat_drc; /* [enm] Latitude grid direction */ lat_typ=rgr->lat_typ; /* [enm] Latitude grid type */ lon_typ=rgr->lon_typ; /* [enm] Longitude grid type */ lat_nbr=rgr->lat_nbr; /* [nbr] Number of latitudes in grid */ lon_nbr=rgr->lon_nbr; /* [nbr] Number of longitudes in grid */ lat_crv=rgr->lat_crv; /* [dgr] Latitude curvilinearity */ lon_crv=rgr->lon_crv; /* [dgr] Longitude curvilinearity */ lat_sth=rgr->lat_sth; /* [dgr] Latitude of southern edge of grid */ lon_wst=rgr->lon_wst; /* [dgr] Longitude of western edge of grid */ lat_nrt=rgr->lat_nrt; /* [dgr] Latitude of northern edge of grid */ lon_est=rgr->lon_est; /* [dgr] Longitude of eastern edge of grid */ /* Use curvilinear coordinates (lat and lon are 2D arrays) if flg_crv already set or it lat_crv or lon_crv set */ if(lat_crv != 0.0 || lon_crv != 0.0 || rgr->flg_crv) flg_grd_crv=True; if(lat_drc == nco_grd_lat_drc_n2s) flg_s2n=False; /* Assume 2D grid */ flg_grd_2D=True; grd_rnk_nbr=dmn_nbr_2D; /* Assume quadrilaterals */ grd_crn_nbr=4; /* Assume rectangles */ bnd_nbr=2; col_nbr=lat_nbr*lon_nbr; grd_sz_nbr=lat_nbr*lon_nbr; /* Allocate space for output data */ area=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); dmn_sz_int=(int *)nco_malloc(grd_rnk_nbr*nco_typ_lng((nc_type)NC_INT)); msk=(int *)nco_malloc(grd_sz_nbr*nco_typ_lng((nc_type)NC_INT)); lat_bnd=(double *)nco_malloc(lat_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(lat_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lon_bnd=(double *)nco_malloc(lon_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(lon_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(lon_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); wgt_Gss=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); grd_ctr_lat=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_ctr_lon=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lat=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lon=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); /* Define variable values */ int lon_psn=int_CEWI; /* [idx] Ordinal position of longitude in rectangular grid dimension-size array */ int lat_psn=int_CEWI; /* [idx] Ordinal position of latitude in rectangular grid dimension-size array */ if(grd_rnk_nbr == dmn_nbr_2D){ lon_psn=0; /* SCRIP introduced [lon,lat] convention because more natural for Fortran */ lat_psn=1; } /* !flg_grd_in_2D */ dmn_sz_int[lon_psn]=lon_nbr; dmn_sz_int[lat_psn]=lat_nbr; for(idx=0;idx<grd_sz_nbr;idx++) msk[idx]=1; /* Compute rectangular arrays NB: Much is a more-generic rewrite of map/map_grd.F90:map_grd_mk() */ /* 20150827: Old rule: Longitude grid was entirely specified by one of four longitude map tokens: Grn_ctr,Grn_wst,180_ctr,180_wst New rule: User may specify bounds (lon_wst,lon_est,lat_sth,lat_nrt) independently of grid token Such bounds ALWAYS refer bounding box interface edges, NEVER to centers of first last gridcells Bounds and number of gridcells completely determine uniform grid so former longitude-type tokens have no effect when bounds specified (so letting grid-type tokens affect grid would over-determine grid and lead to errors) Hence, grid-type tokens may be used as short-hand to specify grids but may not be required to exist later (because regional grids would not have specified them) Grid grid-type tokens lon_bb/lat_bb imply bounding box was originally used to specify bounds 1x1 degree global grid with first longitude centered at Greenwich: --lon_nbr=360 --lon_typ Grn_ctr --lon_nbr=360 --lon_wst=-0.5 --lon_est=359.5 1x1 degree global grid with Greenwich at west edge of first longitude: --lon_nbr=360 --lon_typ Grn_wst --lon_nbr=360 --lon_wst=0.0 --lon_est=360.0 1x1 degree regional grid, total size 9x9 degrees, Greenwich at center of middle gridcell: --lon_nbr=9 --lon_wst=-4.5 --lon_est=4.5 1x1 degree regional grid, total size 10x10 degrees, Greenwich at east/west edges of middle two gridcells --lon_nbr=10 --lon_wst=-5.0 --lon_est=5.0 */ /* Were east/west longitude bounds set explicitly or implicitly? NB: This is redundant since it was done in nco_rgr_ini(), yet better safe than sorry */ if(lon_wst != NC_MAX_DOUBLE || lon_est != NC_MAX_DOUBLE) lon_typ=rgr->lon_typ=nco_grd_lon_bb; if(lon_wst == NC_MAX_DOUBLE){ /* Precomputed longitude grids begin with longitude 0.0 or -180.0 degrees */ switch(lon_typ){ case nco_grd_lon_bb: case nco_grd_lon_Grn_ctr: case nco_grd_lon_Grn_wst: lon_wst=0.0; break; case nco_grd_lon_180_ctr: case nco_grd_lon_180_wst: lon_wst=-180.0; break; default: nco_dfl_case_generic_err(); break; } /* !lon_typ */ } /* !lon */ if(lon_est == NC_MAX_DOUBLE){ /* Precomputed longitude grids end with longitude 360.0 or 180.0 degrees */ switch(lon_typ){ case nco_grd_lon_bb: case nco_grd_lon_Grn_ctr: case nco_grd_lon_Grn_wst: lon_est=360.0; break; case nco_grd_lon_180_ctr: case nco_grd_lon_180_wst: lon_est=180.0; break; default: nco_dfl_case_generic_err(); break; } /* !lon_typ */ } /* !lon */ /* Determine longitude increment from span of pre-centered bounding box (centering will not change span) */ lon_spn=lon_est-lon_wst; lon_ncr=lon_spn/lon_nbr; /* Centering: If user did not set explicit longitude bounds then... */ if(lon_typ != nco_grd_lon_bb) /* map_lon_ctr_typ determines whether lon_wst refers to cell center or Western edge */ if((lon_typ == nco_grd_lon_Grn_ctr) || (lon_typ == nco_grd_lon_180_ctr)) lon_wst=lon_wst-(lon_ncr/2.0); /* Re-derive lon_est from lon_wst and lon_nbr (more fundamental properties) */ lon_est=lon_wst+lon_ncr*lon_nbr; /* lon_wst and lon_est have been set and will not change */ assert(lon_wst < lon_est); lon_ntf[0L]=lon_wst; lon_ntf[lon_nbr]=lon_est; for(lon_idx=1L;lon_idx<lon_nbr;lon_idx++) lon_ntf[lon_idx]=lon_ntf[0L]+lon_idx*lon_ncr; /* Ensure rounding errors do not produce unphysical grid */ lon_ntf[lon_nbr]=lon_ntf[0L]+lon_spn; /* Finished with longitude, now tackle latitude */ /* Were south/north latitude bounds set explicitly or implicitly? */ // if(lat_sth != NC_MAX_DOUBLE || lat_nrt != NC_MAX_DOUBLE) lon_typ=rgr->lat_typ=nco_grd_lat_bb; if(lat_sth == NC_MAX_DOUBLE) lat_sth=-90.0; if(lat_nrt == NC_MAX_DOUBLE) lat_nrt=90.0; /* Determine latitude increment from span of pre-centered bounding box (centering will not change span) */ lat_spn=lat_nrt-lat_sth; lat_ncr=lat_spn/lat_nbr; const long lat_nbr_hlf=lat_nbr/2L; // [nbr] Half number of latitudes (e.g., lat_nbr_hlf=32 for lat_nbr=64 and 65) double *lat_sin=NULL; // [frc] Sine of Gaussian latitudes double precision /* Create S->N grid. If user requested N->S, flip grid at end */ // if(flg_s2n) lat_ntf[0L]=lat_sth; else lat_ntf[0L]=lat_nrt; lat_ntf[0L]=lat_sth; switch(lat_typ){ case nco_grd_lat_fv: lat_ncr=lat_spn/(lat_nbr-1L); lat_ntf[1L]=lat_ntf[0L]+0.5*lat_ncr; for(lat_idx=2L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=lat_ntf[1L]+(lat_idx-1L)*lat_ncr; break; case nco_grd_lat_eqa: lat_ncr=lat_spn/lat_nbr; for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=lat_ntf[0L]+lat_idx*lat_ncr; break; case nco_grd_lat_gss: lat_sin=(double *)nco_malloc(lat_nbr*sizeof(double)); (void)nco_lat_wgt_gss(lat_nbr,True,lat_sin,wgt_Gss); for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=rdn2dgr*asin(lat_sin[lat_idx]); /* First guess for lat_ntf is midway between Gaussian abscissae */ for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=0.5*(lat_ctr[lat_idx-1L]+lat_ctr[lat_idx]); /* Iterate guess until area between interfaces matches Gaussian weight (compute for one hemisphere, make other symmetric) */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++){ double fofx_at_x0; /* [frc] Function to iterate evaluated at current guess */ double dfdx_at_x0; /* [frc] Derivative of equation evaluated at current guess */ const double eps_rlt_cnv=1.0e-15; // Convergence criterion (1.0e-16 pushes double precision to the brink) itr_cnt=0; lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; while(fabs(fofx_at_x0) > eps_rlt_cnv){ /* Newton-Raphson iteration: Let x=lat_ntf[lat_idx], y0=lat_ntf[lat_idx-1L], gw = Gaussian weight (exact solution) f(x)=sin(dgr2rdn*x)-sin(dgr2rdn*y0)-gw=0 # s2n grid f(x)=sin(dgr2rdn*y0)-sin(dgr2rdn*x)-gw=0 # n2s grid dfdx(x)= dgr2rdn*cos(dgr2rdn*x) # s2n grid dfdx(x)=-dgr2rdn*cos(dgr2rdn*x) # n2s grid x_better=x0-f(x0)/f'(x0) */ dfdx_at_x0=dgr2rdn*cos(dgr2rdn*lat_ntf[lat_idx]); /* 20190613: n2s latitudes are constructed s2n and flipped to n2s later Hence next line is commented-out in construction mode but used in infer mode */ // if(!flg_s2n) dfdx_at_x0=-dfdx_at_x0; lat_ntf[lat_idx]+=fofx_at_x0/dfdx_at_x0; /* NB: not sure why this is minus not plus but it works :) */ lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; if(++itr_cnt > itr_nbr_max){ (void)fprintf(stdout,"%s: ERROR %s reports convergence only %g after %d iterations for lat_idx = %ld\n",nco_prg_nm_get(),fnc_nm,fabs(fofx_at_x0),itr_nbr_max,lat_idx); nco_exit(EXIT_FAILURE); } /* endif */ } /* !while */ } /* !lat_idx */ /* Use Gaussian grid symmetry to obtain same interfaces in both hemispheres (avoids cumulative rounding errors) */ if(lat_nbr%2){ /* lat_nbr is odd */ for(lat_idx=1L;lat_idx<=lat_nbr_hlf+1L;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx+1L]; }else{ /* lat_nbr is even */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx]; } /* !flg_lat_evn */ break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ /* Ensure rounding errors do not produce unphysical grid */ lat_ntf[lat_nbr]=lat_nrt; if(nco_dbg_lvl_get() > nco_dbg_old){ (void)fprintf(stderr,"%s: DEBUG %s Gaussian abscissae/interfaces for lat_nbr=%ld\n",nco_prg_nm_get(),fnc_nm,lat_nbr); (void)fprintf(stderr,"idx\tlat_ctr\tlat_ntf\tntf_p1\n"); for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ (void)fprintf(stderr,"%ld\t%20.15f\t%20.15f\t%20.15f\n",lat_idx,lat_ctr[lat_idx],lat_ntf[lat_idx],lat_ntf[lat_idx+1L]); } /* !lat_idx */ } /* !dbg */ /* Always define longitude centers midway between interfaces */ for(lon_idx=0L;lon_idx<=lon_nbr-1L;lon_idx++) lon_ctr[lon_idx]=0.5*(lon_ntf[lon_idx]+lon_ntf[lon_idx+1L]); /* Many grids have center latitude equally spaced between interfaces */ if(lat_typ != nco_grd_lat_fv && lat_typ != nco_grd_lat_gss){ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=0.5*(lat_ntf[lat_idx]+lat_ntf[lat_idx+1L]); } /* !lat_typ */ /* Cap grids excepted---they place centers of first/last gridcells at poles */ if(lat_typ == nco_grd_lat_fv){ lat_ctr[0L]=lat_ntf[0L]; for(lat_idx=1L;lat_idx<lat_nbr-1L;lat_idx++) lat_ctr[lat_idx]=0.5*(lat_ntf[lat_idx]+lat_ntf[lat_idx+1L]); lat_ctr[lat_nbr-1L]=lat_ntf[lat_nbr]; } /* !cap */ /* Gaussian grid centerpoints are defined by solutions to Legendre polynomials */ if(lat_typ == nco_grd_lat_gss){ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=rdn2dgr*asin(lat_sin[lat_idx]); } /* !Gaussian */ for(idx=0L;idx<lon_nbr;idx++){ lon_bnd[2*idx]=lon_ntf[idx]; lon_bnd[2*idx+1L]=lon_ntf[idx+1L]; } /* !idx */ for(idx=0L;idx<lat_nbr;idx++){ lat_bnd[2*idx]=lat_ntf[idx]; lat_bnd[2*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0L;idx<lat_nbr;idx++){ (void)fprintf(stdout,"lat[%li] = %g, vertices = ",idx,lat_ctr[idx]); for(int bnd_idx=0L;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lat_bnd[bnd_nbr*idx+bnd_idx],bnd_idx == bnd_nbr-1 ? "]\n" : ", "); } /* end loop over lat */ } /* endif dbg */ /* Use centers and boundaries to diagnose latitude weights */ switch(lat_typ){ case nco_grd_lat_eqa: case nco_grd_lat_fv: for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=fabs(sin(dgr2rdn*lat_ntf[lat_idx+1L])-sin(dgr2rdn*lat_ntf[lat_idx])); break; case nco_grd_lat_gss: for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=wgt_Gss[lat_idx]; break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ /* Fuzzy test of latitude weight normalization 20180903 Tolerance threshold of eps_rlt_max=1.0e-14 is too strict for Gaussian grids somewhere lat_nbr >~ 150 20180904 Tolerance threshold of eps_rlt_max=1.0e-12 allows Gaussian grids like ECMWF O1280 Newton-Raphson method of interface determination may need improvement to fix that Tolerance threshold of 1.0e-14 works for all relevant E3SM Uniform and Cap grids */ //const double eps_rlt_max=1.0e-14; /* [frc] Round-off error tolerance: Used 1.0e-14 until 20180904 */ const double eps_rlt_max=1.0e-12; /* [frc] Round-off error tolerance: Used 1.0e-12 since 20180904 */ lat_wgt_ttl=0.0; for(idx=0L;idx<lat_nbr;idx++) lat_wgt_ttl+=lat_wgt[idx]; if(grd_typ == nco_grd_2D_fv || grd_typ == nco_grd_2D_eqa){ double lat_wgt_ttl_xpc; /* [frc] Expected sum of latitude weights */ lat_wgt_ttl_xpc=fabs(sin(dgr2rdn*lat_bnd[2*(lat_nbr-1)+1L])-sin(dgr2rdn*lat_bnd[0L])); if(fabs(1.0-lat_wgt_ttl/lat_wgt_ttl_xpc) > eps_rlt_max){ (void)fprintf(stdout,"%s: ERROR %s reports grid normalization does not meet precision tolerance eps_rlt_max = %20.15f\nlat_wgt_ttl = %20.15f, lat_wgt_ttl_xpc = %20.15f, lat_wgt_frc = %20.15f, eps_rlt = %20.15f\n",nco_prg_nm_get(),fnc_nm,eps_rlt_max,lat_wgt_ttl,lat_wgt_ttl_xpc,lat_wgt_ttl/lat_wgt_ttl_xpc,1.0-lat_wgt_ttl/lat_wgt_ttl_xpc); nco_exit(EXIT_FAILURE); } /* !imprecise */ } /* !nco_grd_lat_eqa, !nco_grd_lat_fv */ /* 20180831 Code above assumes grids run S->N User can request N->S grids with --rgr lat_drc=n2s If so, flip grid before unrolling into output arrays */ if(!flg_s2n){ double *lat_ctr_tmp=NULL_CEWI; /* [dgr] Temporary Latitude centers of rectangular grid */ double *lat_wgt_tmp=NULL; /* [dgr] Temporary Latitude weights of rectangular grid */ double *lat_ntf_tmp=NULL; /* [dgr] Temporary Latitude interfaces of rectangular grid */ lat_ctr_tmp=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lat_ntf_tmp=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt_tmp=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); long tmp_idx; /* [idx] Temporary index for swapping values */ for(idx=0L;idx<lat_nbr;idx++){ lat_ctr_tmp[idx]=lat_ctr[idx]; lat_wgt_tmp[idx]=lat_wgt[idx]; } /* !idx */ for(idx=0L;idx<lat_nbr;idx++){ tmp_idx=lat_nbr-idx-1L; lat_ctr[idx]=lat_ctr_tmp[tmp_idx]; lat_wgt[idx]=lat_wgt_tmp[tmp_idx]; } /* !idx */ for(idx=0L;idx<lat_nbr+1L;idx++){ lat_ntf_tmp[idx]=lat_ntf[idx]; } /* !idx */ for(idx=0L;idx<lat_nbr+1L;idx++){ tmp_idx=lat_nbr+1L-idx-1L; /* NB: Subtle index difference */ lat_ntf[idx]=lat_ntf_tmp[tmp_idx]; } /* !idx */ for(idx=0L;idx<lat_nbr;idx++){ lat_bnd[2*idx]=lat_ntf[idx]; lat_bnd[2*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ if(lat_ctr_tmp) lat_ctr_tmp=(double *)nco_free(lat_ctr_tmp); if(lat_ntf_tmp) lat_ntf_tmp=(double *)nco_free(lat_ntf_tmp); if(lat_wgt_tmp) lat_wgt_tmp=(double *)nco_free(lat_wgt_tmp); } /* !flg_s2n */ assert(grd_crn_nbr == 4); for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++){ idx=grd_crn_nbr*lon_idx; lon_crn[idx]=lon_ntf[lon_idx]; lon_crn[idx+1L]=lon_ntf[lon_idx+1L]; lon_crn[idx+2L]=lon_ntf[lon_idx+1L]; lon_crn[idx+3L]=lon_ntf[lon_idx]; } /* !lon_idx */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ idx=grd_crn_nbr*lat_idx; lat_crn[idx]=lat_ntf[lat_idx]; lat_crn[idx+1L]=lat_ntf[lat_idx]; lat_crn[idx+2L]=lat_ntf[lat_idx+1L]; lat_crn[idx+3L]=lat_ntf[lat_idx+1L]; } /* !lat_idx */ /* Stuff rectangular arrays into unrolled arrays */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++){ idx=lat_idx*lon_nbr+lon_idx; grd_ctr_lat[idx]=lat_ctr[lat_idx]; grd_ctr_lon[idx]=lon_ctr[lon_idx]; for(crn_idx=0L;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; lat_idx2=lat_idx*grd_crn_nbr+crn_idx; lon_idx2=lon_idx*grd_crn_nbr+crn_idx; grd_crn_lat[idx2]=lat_crn[lat_idx2]; grd_crn_lon[idx2]=lon_crn[lon_idx2]; } /* !crn */ } /* !lon */ } /* !lat */ if(flg_grd_crv){ /* Impose curvilinearity by adding lon_crv offset to each row relative to previous row, and lat_crv offset to each column relative to previous column */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++){ idx=lat_idx*lon_nbr+lon_idx; grd_ctr_lat[idx]+=lon_idx*lat_crv; grd_ctr_lon[idx]+=lat_idx*lon_crv; for(crn_idx=0L;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; lat_idx2=lat_idx*grd_crn_nbr+crn_idx; lon_idx2=lon_idx*grd_crn_nbr+crn_idx; grd_crn_lat[idx2]=lat_crn[lat_idx2]; grd_crn_lon[idx2]=lon_crn[lon_idx2]; if(crn_idx == 0L || crn_idx == 1L){ grd_crn_lat[idx2]+=lat_idx*lat_crv; /* LL, LR */ grd_crn_lon[idx2]+=lat_idx*lon_crv; /* LL, LR */ }else if(crn_idx == 2L || crn_idx == 3L){ grd_crn_lat[idx2]+=(lat_idx+1L)*lat_crv; /* UL, UR */ grd_crn_lon[idx2]+=(lat_idx+1L)*lon_crv; /* UL, UR */ } /* !crn */ } /* !crn */ } /* !lon */ } /* !lat */ } /* !flg_grd_crv */ /* 20190613: Convert CW quadrilaterals to CCW quadrilaterals so TempestRemap accepts grids Default construction/inferral method orders corners CCW and CW for s2n and n2s grids, respectively */ if(!flg_s2n){ nco_bool flg_ccw; /* [flg] Gridcell is CCW */ const int rcr_lvl=1; /* [nbr] Recursion level (1 is top level, 2 and greater are recursed */ const int idx_ccw=0; /* [idx] Index of starting vertice for CCW check (Point A = tail side AB) */ for(idx=0L;idx<grd_sz_nbr;idx++){ idx2=grd_crn_nbr*idx; flg_ccw=nco_ccw_chk(grd_crn_lat+idx2,grd_crn_lon+idx2,grd_crn_nbr,idx_ccw,rcr_lvl); if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_vec) (void)fprintf(stderr,"%s: DEBUG %s reports nco_ccw_chk() tried to change idx = %lu from CW to CCW\n",nco_prg_nm_get(),fnc_nm,idx); } /* !idx */ } /* !flg_s2n */ if(nco_dbg_lvl_get() >= nco_dbg_std){ long int idx_crn_ll; long int idx_crn_lr; long int idx_crn_ur; long int idx_crn_ul; long idx_dbg; idx_dbg=rgr->idx_dbg; idx_crn_ll=grd_crn_nbr*idx_dbg+0L; idx_crn_lr=grd_crn_nbr*idx_dbg+1L; idx_crn_ur=grd_crn_nbr*idx_dbg+2L; idx_crn_ul=grd_crn_nbr*idx_dbg+3L; (void)fprintf(stderr,"%s: INFO %s idx_dbg = %li, Center [lat,lon]=[%g,%g]; Corners LL [%g,%g] LR [%g,%g] UR [%g,%g] UL [%g,%g]\n",nco_prg_nm_get(),fnc_nm,idx_dbg,grd_ctr_lat[idx_dbg],grd_ctr_lon[idx_dbg],grd_crn_lat[idx_crn_ll],grd_crn_lon[idx_crn_ll],grd_crn_lat[idx_crn_lr],grd_crn_lon[idx_crn_lr],grd_crn_lat[idx_crn_ur],grd_crn_lon[idx_crn_ur],grd_crn_lat[idx_crn_ul],grd_crn_lon[idx_crn_ul]); } /* !dbg */ if(flg_grd_crv){ /* Area of arbitrary curvilinear grids requires spherical trigonometry */ nco_sph_plg_area(rgr,grd_crn_lat,grd_crn_lon,grd_sz_nbr,grd_crn_nbr,area); }else{ /* Area of rectangular spherical zones from elementary calculus results 20150906: Half-angle formulae for better conditioning improve area normalization for 801x1600 by 2.0e-15 area[lat_idx*lon_nbr+lon_idx]=dgr2rdn*(lon_bnd[2*lon_idx+1L]-lon_bnd[2*lon_idx])*2.0*(sin(0.5*dgr2rdn*lat_bnd[2*lat_idx+1L])*cos(0.5*dgr2rdn*lat_bnd[2*lat_idx+1L])-sin(0.5*dgr2rdn*lat_bnd[2*lat_idx])*cos(0.5*dgr2rdn*lat_bnd[2*lat_idx])); Gain not worth the extra complexity */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++) /* fabs() ensures positive area in n2s grids */ area[lat_idx*lon_nbr+lon_idx]=fabs(dgr2rdn*(lon_bnd[2*lon_idx+1L]-lon_bnd[2*lon_idx])*(sin(dgr2rdn*lat_bnd[2*lat_idx+1L])-sin(dgr2rdn*lat_bnd[2*lat_idx]))); } /* !flg_grd_2D */ if(nco_dbg_lvl_get() >= nco_dbg_sbr){ lat_wgt_ttl=0.0; area_ttl=0.0; if(flg_grd_2D){ (void)fprintf(stderr,"%s: INFO %s reports destination rectangular latitude grid:\n",nco_prg_nm_get(),fnc_nm); for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_wgt_ttl+=lat_wgt[lat_idx]; } /* !flg_grd_2D */ for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0L;lon_idx<lon_nbr;lon_idx++) area_ttl+=area[lat_idx*lon_nbr+lon_idx]; (void)fprintf(stdout,"lat_wgt_ttl = %20.15f, frc_lat_wgt = %20.15f, area_ttl = %20.15f, frc_area = %20.15f\n",lat_wgt_ttl,lat_wgt_ttl/2.0,area_ttl,area_ttl/(4.0*M_PI)); assert(area_ttl > 0.0); assert(area_ttl <= 4.0*M_PI); } /* endif dbg */ /* Open grid file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Define dimensions */ rcd=nco_def_dim(out_id,grd_crn_nm,grd_crn_nbr,&dmn_id_grd_crn); rcd=nco_def_dim(out_id,grd_sz_nm,grd_sz_nbr,&dmn_id_grd_sz); rcd=nco_def_dim(out_id,grd_rnk_nm,grd_rnk_nbr,&dmn_id_grd_rnk); int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; /* Define variables */ (void)nco_def_var(out_id,dmn_sz_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_rnk,&dmn_sz_int_id); /* NB: Too small to deflate */ (void)nco_def_var(out_id,grd_area_nm,(nc_type)crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,msk_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_sz,&msk_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lat_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lon_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lon_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_grd_sz; dmn_ids[1]=dmn_id_grd_crn; (void)nco_def_var(out_id,grd_crn_lat_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lat_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_grd_sz; dmn_ids[1]=dmn_id_grd_crn; (void)nco_def_var(out_id,grd_crn_lon_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lon_id,shuffle,deflate,dfl_lvl); /* Define global and "units" attributes */ char *att_val; rcd=nco_char_att_put(out_id,NULL,"title",rgr->grd_ttl); rcd=nco_char_att_put(out_id,NULL,"Conventions","SCRIP"); const char usr_cpp[]=TKN2SNG(USER); /* [sng] Hostname from C pre-processor */ rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); rcd=nco_char_att_put(out_id,NULL,"grid_generator","NCO"); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,NULL,"latitude_grid_type",nco_grd_lat_sng(lat_typ)); rcd=nco_char_att_put(out_id,NULL,"longitude_grid_type",nco_grd_lon_sng(lon_typ)); rcd=nco_char_att_put(out_id,dmn_sz_nm,"long_name","Size(s) of horizontal dimensions (in Fortran storage order for historical reasons)"); rcd=nco_char_att_put(out_id,grd_area_nm,"long_name","Solid Angle Subtended on Source Grid"); rcd=nco_char_att_put(out_id,grd_area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,grd_area_nm,"units","steradian"); rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"standard_name","latitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"bounds",grd_crn_lat_nm); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"standard_name","longitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees_east"); else rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"bounds",grd_crn_lon_nm); rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"long_name","Latitude of Grid Cell Vertices"); rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"standard_name","latitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"long_name","Longitude of Grid Cell Vertices"); rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"standard_name","longitude"); if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees_east"); else rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees"); /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ rcd=nco_char_att_put(out_id,msk_nm,"long_name","Binary Integer Mask for Grid"); rcd=nco_char_att_put(out_id,msk_nm,"units","none"); /* Begin data mode */ (void)nco_enddef(out_id); /* Write variables */ dmn_srt[0]=0L; dmn_cnt[0]=grd_rnk_nbr; rcd=nco_put_vara(out_id,dmn_sz_int_id,dmn_srt,dmn_cnt,dmn_sz_int,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,msk_id,dmn_srt,dmn_cnt,msk,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lat_id,dmn_srt,dmn_cnt,grd_ctr_lat,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lon_id,dmn_srt,dmn_cnt,grd_ctr_lon,crd_typ); dmn_srt[0]=0L; dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lat_id,dmn_srt,dmn_cnt,grd_crn_lat,crd_typ); dmn_srt[0]=0L; dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lon_id,dmn_srt,dmn_cnt,grd_crn_lon,crd_typ); /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); fl_out=rgr->fl_skl; if(fl_out){ /* Write skeleton data file on requested grid Skeleton file can then be populated with data for testing */ char *area_nm; char *bnd_nm; // char *bnd_tm_nm; char *col_nm_out; char *lat_nm_out; /* [sng] Name of output dimension for latitude */ char *lat_wgt_nm; char *lon_nm_out; /* [sng] Name of variable to recognize as longitude */ char *lat_bnd_nm; /* [sng] Name of latitude boundary variable */ char *lon_bnd_nm; /* [sng] Name of longitude boundary variable */ // int area_id; /* [id] Variable ID for area */ int dmn_id_bnd; /* [id] Dimension ID */ //int dmn_id_bnd_tm; /* [id] Dimension ID */ int dmn_id_col; /* [id] Dimension ID */ int dmn_id_lat; /* [id] Dimension ID */ int dmn_id_lon; /* [id] Dimension ID */ int lat_bnd_id; /* [id] Variable ID for lat_bnds/lat_vertices */ int lat_id; /* [id] Variable ID for latitude */ int lat_wgt_id; /* [id] Variable ID for latitude weight */ int lon_bnd_id; /* [id] Variable ID for lon_bnds/lon_vertices */ int lon_id; /* [id] Variable ID for longitude */ /* Use explicitly specified output names, if any, otherwise use input names (either explicitly specified or discovered by fuzzing) */ if(rgr->lat_nm_out) lat_nm_out=rgr->lat_nm_out; else lat_nm_out=(char *)strdup("lat"); if(rgr->lon_nm_out) lon_nm_out=rgr->lon_nm_out; else lon_nm_out=(char *)strdup("lon"); if(rgr->col_nm_out) col_nm_out=rgr->col_nm_out; else col_nm_out=(char *)strdup("ncol"); /* Name output dimensions */ area_nm=rgr->area_nm; bnd_nm=rgr->bnd_nm; //bnd_tm_nm=rgr->bnd_tm_nm; lat_bnd_nm=rgr->lat_bnd_nm; lat_wgt_nm=rgr->lat_wgt_nm; lon_bnd_nm=rgr->lon_bnd_nm; /* Use names discovered by fuzzing */ if(flg_grd_1D){ bnd_nm=rgr->vrt_nm; lat_bnd_nm=rgr->lat_vrt_nm; lon_bnd_nm=rgr->lon_vrt_nm; } /* !flg_grd_1D */ if(flg_grd_2D){ bnd_nm=rgr->bnd_nm; lat_bnd_nm=rgr->lat_bnd_nm; lon_bnd_nm=rgr->lon_bnd_nm; } /* !flg_grd_2D */ /* Open grid file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Define dimensions */ if(flg_grd_crv){ rcd=nco_def_dim(out_id,bnd_nm,grd_crn_nbr,&dmn_id_bnd); }else{ rcd=nco_def_dim(out_id,bnd_nm,bnd_nbr,&dmn_id_bnd); } /* !flg_grd_crv */ if(flg_grd_1D){ rcd=nco_def_dim(out_id,col_nm_out,col_nbr,&dmn_id_col); } /* !flg_grd_1D */ if(flg_grd_2D){ rcd=nco_def_dim(out_id,lat_nm_out,lat_nbr,&dmn_id_lat); rcd=nco_def_dim(out_id,lon_nm_out,lon_nbr,&dmn_id_lon); } /* !flg_grd_2D */ /* Define new coordinates and variables in regridded file */ if(flg_grd_1D){ (void)nco_def_var(out_id,lat_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_col,&lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_col,&lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_col; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lat_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_col; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lon_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_1D,&dmn_id_col,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); } /* !flg_grd_1D */ if(flg_grd_crv){ dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_lon; (void)nco_def_var(out_id,lat_nm_out,crd_typ,dmn_nbr_2D,dmn_ids,&lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_nm_out,crd_typ,dmn_nbr_2D,dmn_ids,&lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_2D,dmn_ids,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_lon; dmn_ids[2]=dmn_id_bnd; (void)nco_def_var(out_id,lat_bnd_nm,crd_typ,dmn_nbr_3D,dmn_ids,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_bnd_nm,crd_typ,dmn_nbr_3D,dmn_ids,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); }else if(flg_grd_2D){ (void)nco_def_var(out_id,lat_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_lat,&lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lon_nm_out,crd_typ,dmn_nbr_1D,&dmn_id_lon,&lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lat_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lat_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lon; dmn_ids[1]=dmn_id_bnd; (void)nco_def_var(out_id,lon_bnd_nm,crd_typ,dmn_nbr_2D,dmn_ids,&lon_bnd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,lat_wgt_nm,crd_typ,dmn_nbr_1D,&dmn_id_lat,&lat_wgt_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_wgt_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_lat; dmn_ids[1]=dmn_id_lon; (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_2D,dmn_ids,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); } /* !flg_grd_2D */ /* Define attributes */ rcd=nco_char_att_put(out_id,NULL,"title",rgr->grd_ttl); rcd=nco_char_att_put(out_id,NULL,"Conventions","CF-1.6"); rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,NULL,"latitude_grid_type",nco_grd_lat_sng(lat_typ)); rcd=nco_char_att_put(out_id,NULL,"longitude_grid_type",nco_grd_lon_sng(lon_typ)); rcd=nco_char_att_put(out_id,area_nm,"long_name","Solid angle subtended by gridcell"); rcd=nco_char_att_put(out_id,area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm,"units","steradian"); char *crd_val_sng; /* CF-standard coordinates values string */ size_t crd_val_sng_lng=strlen(lat_nm_out)+strlen(lon_nm_out)+1L; crd_val_sng=(char *)nco_malloc(crd_val_sng_lng*sizeof(char)+1L); (void)sprintf(crd_val_sng,"%s %s",lat_nm_out,lon_nm_out); rcd=nco_char_att_put(out_id,area_nm,"coordinates",crd_val_sng); if(crd_val_sng) crd_val_sng=(char *)nco_free(crd_val_sng); rcd=nco_char_att_put(out_id,lat_nm_out,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lat_nm_out,"standard_name","latitude"); rcd=nco_char_att_put(out_id,lat_nm_out,"units","degrees_north"); rcd=nco_char_att_put(out_id,lat_nm_out,"axis","Y"); rcd=nco_char_att_put(out_id,lat_nm_out,"bounds",lat_bnd_nm); if(flg_grd_2D) att_val=strdup("Gridcell latitude interfaces"); else att_val=strdup("Gridcell latitude vertices"); rcd=nco_char_att_put(out_id,lat_bnd_nm,"long_name",att_val); if(flg_grd_2D) rcd=nco_char_att_put(out_id,lat_wgt_nm,"long_name","Latitude quadrature weights (normalized to sum to 2.0 on global grids)"); rcd=nco_char_att_put(out_id,lon_nm_out,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,lon_nm_out,"standard_name","longitude"); rcd=nco_char_att_put(out_id,lon_nm_out,"units","degrees_east"); rcd=nco_char_att_put(out_id,lon_nm_out,"axis","X"); rcd=nco_char_att_put(out_id,lon_nm_out,"bounds",lon_bnd_nm); if(flg_grd_2D) att_val=strdup("Gridcell longitude interfaces"); else att_val=strdup("Gridcell longitude vertices"); rcd=nco_char_att_put(out_id,lon_bnd_nm,"long_name",att_val); /* Begin data mode */ (void)nco_enddef(out_id); /* Write new coordinates and variables to regridded file */ if(flg_grd_1D){ dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; (void)nco_put_vara(out_id,lat_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; (void)nco_put_vara(out_id,lon_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=col_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; (void)nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); } /* !flg_grd_1D */ if(flg_grd_crv){ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; (void)nco_put_vara(out_id,lat_id,dmn_srt,dmn_cnt,grd_ctr_lat,crd_typ); (void)nco_put_vara(out_id,lon_id,dmn_srt,dmn_cnt,grd_ctr_lon,crd_typ); (void)nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); dmn_srt[0]=dmn_srt[1]=0L;dmn_srt[2]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; dmn_cnt[2]=grd_crn_nbr; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt,dmn_cnt,grd_crn_lat,crd_typ); (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt,dmn_cnt,grd_crn_lon,crd_typ); }else if(flg_grd_2D){ dmn_srt[0]=0L; dmn_cnt[0]=lat_nbr; (void)nco_put_vara(out_id,lat_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=lon_nbr; (void)nco_put_vara(out_id,lon_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=lat_nbr; (void)nco_put_vara(out_id,lat_wgt_id,dmn_srt,dmn_cnt,lat_wgt,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lon_nbr; dmn_cnt[1]=bnd_nbr; (void)nco_put_vara(out_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; (void)nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); } /* !flg_grd_2D */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); } /* !fl_out */ /* Free memory associated with input file */ if(dmn_sz_int) dmn_sz_int=(int *)nco_free(dmn_sz_int); if(msk) msk=(int *)nco_free(msk); if(area) area=(double *)nco_free(area); if(grd_ctr_lat) grd_ctr_lat=(double *)nco_free(grd_ctr_lat); if(grd_ctr_lon) grd_ctr_lon=(double *)nco_free(grd_ctr_lon); if(grd_crn_lat) grd_crn_lat=(double *)nco_free(grd_crn_lat); if(grd_crn_lon) grd_crn_lon=(double *)nco_free(grd_crn_lon); if(lat_bnd) lat_bnd=(double *)nco_free(lat_bnd); if(lat_crn) lat_crn=(double *)nco_free(lat_crn); if(lat_ctr) lat_ctr=(double *)nco_free(lat_ctr); if(lat_ntf) lat_ntf=(double *)nco_free(lat_ntf); if(lat_sin) lat_sin=(double *)nco_free(lat_sin); if(lat_wgt) lat_wgt=(double *)nco_free(lat_wgt); if(lon_bnd) lon_bnd=(double *)nco_free(lon_bnd); if(lon_crn) lon_crn=(double *)nco_free(lon_crn); if(lon_ctr) lon_ctr=(double *)nco_free(lon_ctr); if(lon_ntf) lon_ntf=(double *)nco_free(lon_ntf); if(wgt_Gss) wgt_Gss=(double *)nco_free(wgt_Gss); return rcd; } /* !nco_grd_mk() */ int /* O [enm] Return code */ nco_grd_nfr /* [fnc] Infer SCRIP-format grid file from input data file */ (rgr_sct * const rgr) /* I/O [sct] Regridding structure */ { /* Purpose: Use grid information and guesswork to create SCRIP-format grid file from input data file Test curvilinear grids: ncks -O -D 1 --rgr infer --rgr grid=${DATA}/sld/rgr/grd_airs.nc ${DATA}/sld/raw/AIRS.2014.10.01.202.L2.TSurfStd.Regrid010.1DLatLon.nc ~/foo.nc ncks -O -D 1 --rgr infer --rgr grid=${DATA}/sld/rgr/grd_airs.nc ${DATA}/sld/raw/AIRS.2014.10.01.202.L2.TSurfStd.Regrid010.1DLatLon.hole.nc ~/foo.nc */ const char fnc_nm[]="nco_grd_nfr()"; /* [sng] Function name */ const double rdn2dgr=180.0/M_PI; const double dgr2rdn=M_PI/180.0; const int dmn_nbr_0D=0; /* [nbr] Rank of 0-D grid variables */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ const int dmn_nbr_grd_max=4; /* [nbr] Maximum rank of grid variables (msk_[src/dst] could be rank 4) */ const int itr_nbr_max=20; // [nbr] Maximum number of iterations const int idx_ccw=0; /* [idx] Index of starting vertice for CCW check (Point A = tail side AB) */ const int rcr_lvl=1; /* [nbr] Recursion level (1 is top level, 2 and greater are recursed */ const nc_type crd_typ=NC_DOUBLE; char *area_nm_in=NULL; char *fl_in; char *fl_out; char *fl_out_tmp=NULL_CEWI; char *fl_pth_lcl=NULL; char *msk_nm_in=NULL; char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ /* SCRIP-format grid names are non-negotiable and thus fixed not dynamic */ char area_nm[]="grid_area"; /* 20150830: NB ESMF_RegridWeightGen --user_areas looks for variable named "grid_area" */ char dmn_sz_nm[]="grid_dims"; char grd_crn_lat_nm[]="grid_corner_lat"; char grd_crn_lon_nm[]="grid_corner_lon"; char grd_crn_nm[]="grid_corners"; char grd_ctr_lat_nm[]="grid_center_lat"; char grd_ctr_lon_nm[]="grid_center_lon"; char grd_rnk_nm[]="grid_rank"; char grd_sz_nm[]="grid_size"; char msk_nm[]="grid_imask"; char unt_sng[]="units"; /* netCDF-standard units attribute name */ double *grd_ctr_lat; /* [dgr] Latitude centers of grid */ double *grd_ctr_lon; /* [dgr] Longitude centers of grid */ double *grd_crn_lat; /* [dgr] Latitude corners of grid */ double *grd_crn_lon; /* [dgr] Longitude corners of grid */ double *area; /* [sr] Area of grid */ double *lat_bnd=NULL_CEWI; /* [dgr] Latitude boundaries of rectangular grid */ double *lat_crn=NULL; /* [dgr] Latitude corners of rectangular grid */ double *lat_ctr=NULL_CEWI; /* [dgr] Latitude centers of rectangular grid */ double *lat_ntf=NULL; /* [dgr] Latitude interfaces of rectangular grid */ double *lat_wgt=NULL; /* [dgr] Latitude weights of rectangular grid */ double *lon_bnd=NULL_CEWI; /* [dgr] Longitude boundaries of rectangular grid */ double *lon_crn=NULL; /* [dgr] Longitude corners of rectangular grid */ double *lon_ctr=NULL_CEWI; /* [dgr] Longitude centers of rectangular grid */ double *lon_ntf=NULL; /* [dgr] Longitude interfaces of rectangular grid */ double *vrt_lat=NULL; /* [rdn] MPAS latitude boundary variable latVertex */ double *vrt_lon=NULL; /* [rdn] MPAS longitude boundary variable lonVertex */ double area_ttl=0.0; /* [frc] Exact sum of area */ //double lat_nrt; /* [dgr] Latitude of northern edge of grid */ double lat_sth; /* [dgr] Latitude of southern edge of grid */ double lat_wgt_ttl=0.0; /* [frc] Actual sum of quadrature weights */ double lat_wgt_gss; /* [frc] Latitude weight estimated from interface latitudes */ // double lon_est; /* [dgr] Longitude of eastern edge of grid */ double lon_wst; /* [dgr] Longitude of western edge of grid */ double lon_ncr; /* [dgr] Longitude increment */ double lat_ncr; /* [dgr] Latitude increment */ double lon_spn; /* [dgr] Longitude span */ double lat_spn; /* [dgr] Latitude span */ double mss_val_area_dbl; double mss_val_ctr_dbl; double mss_val_msk_dbl; int *msk=NULL; /* [flg] Mask of grid */ int *edg_nbr_cll=NULL; /* [enm] MPAS variable nEdgesOnCell */ int *vrt_cll=NULL; /* [enm] MPAS variable verticesOnCell */ int *dmn_sz_int; /* [nbr] Array of dimension sizes of grid */ int dmn_ids[dmn_nbr_grd_max]; /* [id] Dimension IDs array for output variable */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int dmn_idx; /* [idx] Dimension index */ int fl_out_fmt=NC_FORMAT_CLASSIC; /* [enm] Output file format */ int in_id; /* I [id] Input netCDF file ID */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int area_id=NC_MIN_INT; /* [id] Area variable ID */ int dmn_id_grd_crn; /* [id] Grid corners dimension ID */ int dmn_id_grd_rnk; /* [id] Grid rank dimension ID */ int dmn_id_grd_sz; /* [id] Grid size dimension ID */ int dmn_sz_int_id; /* [id] Grid dimension sizes ID */ int grd_crn_lat_id; /* [id] Grid corner latitudes variable ID */ int grd_crn_lon_id; /* [id] Grid corner longitudes variable ID */ int grd_ctr_lat_id; /* [id] Grid center latitudes variable ID */ int grd_ctr_lon_id; /* [id] Grid center longitudes variable ID */ int itr_cnt; /* Iteration counter */ int lat_rnk; /* [nbr] Rank of latitude coordinate */ int lon_rnk; /* [nbr] Rank of longitude coordinate */ int lat_ctr_id=NC_MIN_INT; /* [id] Latitude centers of rectangular grid variable ID */ int lon_ctr_id=NC_MIN_INT; /* [id] Longitude centers of rectangular grid variable ID */ int lat_bnd_id=NC_MIN_INT; /* [id] Latitude centers of rectangular grid variable ID */ int lon_bnd_id=NC_MIN_INT; /* [id] Longitude centers of rectangular grid variable ID */ int msk_id=NC_MIN_INT; /* [id] Mask variable ID */ int msk_rnk_nbr; /* [id] Mask rank */ int mss_val_int_out=NC_MIN_INT; /* [nbr] Value that can be non-erroneously pointed to */ int val_two=2; /* [nbr] Value that can be non-erroneously pointed to */ int val_zero=0; /* [nbr] Value that can be non-erroneously pointed to */ int var_id; /* [id] Current variable ID */ int edg_nbr_cll_id=NC_MIN_INT; /* [id] MPAS variable nEdgesOnCell ID */ int vrt_cll_id=NC_MIN_INT; /* [id] MPAS variable verticesOnCell ID */ int vrt_lat_id=NC_MIN_INT; /* [id] MPAS latitude boundary variable latVertex ID */ int vrt_lon_id=NC_MIN_INT; /* [id] MPAS longitude boundary variable lonVertex ID */ long dmn_srt[dmn_nbr_grd_max]; long dmn_cnt[dmn_nbr_grd_max]; long bnd_idx; long bnd_nbr=NC_MIN_INT; /* [nbr] Number of bounds in gridcell */ long col_idx; long col_nbr; /* [nbr] Number of columns in grid */ long crn_idx; /* [idx] Counting index for corners */ long ttl_idx; /* [idx] Total (unrolled) counting index for grid+corners */ long dmn_sz; /* [nbr] Size of current dimension */ long grd_crn_nbr; /* [nbr] Number of corners in gridcell */ long grd_rnk_nbr=int_CEWI; /* [nbr] Number of dimensions in grid */ long grd_sz_nbr; /* [nbr] Number of gridcells in grid */ long idx2; /* [idx] Counting index for unrolled grids */ long idx; /* [idx] Counting index for unrolled grids */ long idx_crn; long idx_ctr; long lat_idx2; /* [idx] Counting index for unrolled latitude */ long lat_idx; long lat_nbr; /* [nbr] Number of latitudes in grid */ long lon_idx2; /* [idx] Counting index for unrolled longitude */ long lon_idx; long lon_nbr; /* [nbr] Number of longitudes in grid */ long vrt_idx; /* [idx] Counting index for vertices */ long vrt_nbr; /* [nbr] Number of vertices in MPAS grid */ long int idx_crn_ll; long int idx_crn_lr; long int idx_crn_ur; long int idx_crn_ul; nco_bool FL_RTR_RMT_LCN; nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=True; /* Option O */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=rgr->flg_uio; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=False; /* [flg] Write output to temporary file */ nco_bool flg_1D_mpas_bnd=False; /* [flg] Unstructured input grid with MPAS bounds */ nco_bool flg_1D_psd_rct_bnd=False; /* [flg] Unstructured input grid with pseudo-rectangular bounds */ nco_bool flg_ccw; /* [flg] Gridcell is CCW */ nco_bool flg_grd_1D=False; nco_bool flg_grd_2D=False; nco_bool flg_grd_crv=False; nco_bool flg_s2n=True; /* [enm] Latitude grid-direction is South-to-North */ nco_bool flg_wrt_crn=True; nco_bool flg_crn_grd_lat_lon=False; /* [flg] Curvilinear corner array ordered non-canonically as grd_nbr,lat_nbr,lon_nbr */ nco_bool use_mss_val_area=False; nco_bool has_mss_val_area=False; nco_bool has_mss_val_bnd=False; nco_bool has_mss_val_ctr=False; nco_bool has_mss_val_msk=False; nco_grd_2D_typ_enm grd_typ; /* [enm] Grid-type enum */ nco_grd_lat_typ_enm lat_typ; /* [enm] Latitude grid-type enum */ nco_grd_lon_typ_enm lon_typ; /* [enm] Longitude grid-type enum */ nco_grd_xtn_enm nco_grd_xtn=nco_grd_xtn_nil; /* [enm] Grid-extent enum */ nc_type msk_typ; ptr_unn msk_unn; size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ /* Algorithm: Read grid information from input data file (aka *_in) Close input file Once grid dimensions known, allocate output grid arrays (aka *_out) Open output file (aka grid-file) Use guesswork and standard algorithms to fill-in output arrays */ /* Duplicate (because nco_fl_mk_lcl() free()'s fl_in) */ fl_in=(char *)strdup(rgr->fl_in); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,&in_id); char *bnd_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as bounds */ char *col_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as column */ char *lat_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as latitude */ char *lon_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as longitude */ char *lat_nm_in=NULL_CEWI; /* [sng] Name of variable to recognize as latitude */ char *lon_nm_in=NULL_CEWI; /* [sng] Name of variable to recognize as longitude */ char *lat_bnd_nm=NULL_CEWI; /* [sng] Name of latitude boundary variable */ char *lon_bnd_nm=NULL_CEWI; /* [sng] Name of longitude boundary variable */ char *edg_nbr_cll_nm=NULL_CEWI; /* [sng] Name of MPAS variable nEdgesOnCell */ char *vrt_dmn_nm=NULL_CEWI; /* [sng] Name of MPAS vertices dimension nVertices */ char *vrt_cll_nm=NULL_CEWI; /* [sng] Name of MPAS variable verticesOnCell */ char *vrt_lat_nm=NULL_CEWI; /* [sng] Name of MPAS latitude boundary variable latVertex */ char *vrt_lon_nm=NULL_CEWI; /* [sng] Name of MPAS longitude boundary variable lonVertex */ int dmn_id_bnd=NC_MIN_INT; /* [id] Dimension ID for spatial bounds */ int dmn_id_col=NC_MIN_INT; /* [id] Dimension ID for unstructured grids */ int dmn_id_lat=NC_MIN_INT; /* [id] Dimension ID for latitude */ int dmn_id_lon=NC_MIN_INT; /* [id] Dimension ID for longitude */ int dmn_id_vrt=NC_MIN_INT; /* [id] Dimension ID for MPAS vertices */ /* Begin CF-coordinates block */ cf_crd_sct *cf=NULL; char *rgr_var; /* [sng] Variable for special regridding treatment */ nco_bool flg_cf=False; /* [flg] Follow CF Coordinates convention to find and infer grid */ rgr_var=rgr->var_nm; if(rgr_var){ /* Infer grid from special variable Intended to be variable that has both horizontal dimensions and "coordinates" attribute, e.g., ncks --cdl -m ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc | grep coordinates 4LFTX_221_SPDY_S113:coordinates = "gridlat_221 gridlon_221" ; Usage: ncks -O -D 3 --rgr infer --rgr_var=4LFTX_221_SPDY_S113 --rgr grid=~/grd_narr.nc ${DATA}/hdf/narrmon-a_221_20100101_0000_000.nc ~/foo.nc */ char crd_sng[]="coordinates"; /* CF-standard coordinates attribute name */ cf=(cf_crd_sct *)nco_malloc(sizeof(cf_crd_sct)); cf->crd=False; /* [flg] CF coordinates information is complete */ cf->crd_id[0]=NC_MIN_INT; /* [id] Coordinate ID, first */ cf->crd_id[1]=NC_MIN_INT; /* [id] Coordinate ID, second */ cf->crd_nm[0]=NULL; /* [sng] Coordinate name, first */ cf->crd_nm[1]=NULL; /* [sng] Coordinate name, second */ cf->crd_sng=NULL; /* [sng] Coordinates attribute value */ cf->dmn_id[0]=NC_MIN_INT; /* [id] Dimension ID, first */ cf->dmn_id[1]=NC_MIN_INT; /* [id] Dimension ID, second */ cf->dmn_nm[0]=NULL; /* [sng] Dimension name, first */ cf->dmn_nm[1]=NULL; /* [sng] Dimension name, second */ cf->unt_sng[0]=NULL; /* [sng] Units string, first coordinate */ cf->unt_sng[1]=NULL; /* [sng] Units string, second coordinate */ cf->var_id=NC_MIN_INT; /* [id] Coordinate variable ID */ cf->var_nm=NULL; /* [sng] Coordinates variable name */ cf->var_type=NC_NAT; /* [enm] Coordinates variable type */ if((rcd=nco_inq_varid_flg(in_id,rgr_var,&cf->var_id)) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports special \"coordinates\" variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd */ cf->crd_sng=nco_char_att_get(in_id,cf->var_id,crd_sng); if(cf->crd_sng){ cf->crd=True; }else{ /* !rcd && att_typ */ (void)fprintf(stderr,"%s: WARNING %s reports coordinates variable %s does not have character-valued \"coordinates\" attribute. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,rgr_var); goto skp_cf; } /* !rcd && att_typ */ /* Valid coordinates attribute requires two coordinate names separated by space character */ char *crd_nm[NCO_MAX_CRD_PER_VAR]; /* [sng] Coordinate name start position */ char *crd_dpl; /* [sng] Modifiable duplicate of coordinates string */ char *spc_ptr; /* [sng] Pointer to space character (' ') */ int crd_nbr=0; /* [nbr] Number of names in coordinates attribute */ int crd_spt=0; /* [nbr] Number of "spatial-like" (that include "degree" in units) coordinates */ int crd_idx=0; /* [idx] Counter for coordinate names */ for(crd_idx=0;crd_idx<NCO_MAX_CRD_PER_VAR;crd_idx++) crd_nm[crd_idx]=NULL; crd_dpl=(char *)strdup(cf->crd_sng); /* Search for spaces starting from end of string */ while((spc_ptr=strrchr(crd_dpl,' '))){ crd_nm[crd_nbr]=spc_ptr+1L; crd_nbr++; /* NUL-terminate so next search ends here */ *spc_ptr='\0'; } /* !sbs_ptr */ /* Final coordinate name begins where coordinate string starts */ crd_nm[crd_nbr]=crd_dpl; /* Change crd_nbr from 0-based index to actual coordinate number */ crd_nbr++; if(crd_nbr < 2){ (void)fprintf(stderr,"%s: WARNING %s found only %d coordinate(s) in \"coordinates\" attribute \"%s\", at least two are required. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,crd_nbr,cf->crd_sng); goto skp_cf; } /* !crd_nbr */ /* If more than two coordinate names are present, choose first two (searching backwards from end) with "degree" in units attributes, otherwise just choose first two */ crd_idx=crd_spt=0; while(crd_spt < 2 && crd_idx < crd_nbr){ cf->crd_nm[crd_spt]=crd_nm[crd_idx]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[crd_spt],&cf->crd_id[crd_spt])) == NC_NOERR){ cf->unt_sng[crd_spt]=nco_char_att_get(in_id,cf->crd_id[crd_spt],unt_sng); if(cf->unt_sng[crd_spt]){ if(strcasestr(cf->unt_sng[crd_spt],"degree")){ /* Increment count of spatial-like coordinates... */ crd_spt++; }else{ /* ...or free() memory allocated during search */ cf->unt_sng[crd_spt]=(char *)nco_free(cf->unt_sng[crd_spt]); } /* !strcasestr() */ crd_idx++; } /* !rcd && att_typ */ } /* !rcd */ } /* !crd_spt */ /* If while()-loop above was successful, our search is over Otherwise, use first two coordinate names regardless of units, and print more diagnostics */ if(crd_spt < 2){ cf->crd_nm[0]=crd_nm[0]; cf->crd_nm[1]=crd_nm[1]; if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[0],&cf->crd_id[0])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0]); goto skp_cf; } /* !rcd */ if((rcd=nco_inq_varid_flg(in_id,cf->crd_nm[1],&cf->crd_id[1])) != NC_NOERR){ (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s not found. Turning-off CF coordinates search.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1]); goto skp_cf; } /* !rcd */ cf->unt_sng[0]=nco_char_att_get(in_id,cf->crd_id[0],unt_sng); if(cf->unt_sng[0]){ if(!strcasestr(cf->unt_sng[0],"degree")) (void)fprintf(stderr,"%s: WARNING %s reports first coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->unt_sng[0]); } /* !rcd && att_typ */ cf->unt_sng[1]=nco_char_att_get(in_id,cf->crd_id[1],unt_sng); if(cf->unt_sng[1]){ if(!strcasestr(cf->unt_sng[1],"degree")) (void)fprintf(stderr,"%s: WARNING %s reports second coordinates variable %s has weird units attribute = %s. May not detect correct ordering of latitude and longitude coordinates\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[1],cf->unt_sng[1]); } /* !rcd && att_typ */ } /* !crd_spt */ int crd_rnk; /* [nbr] Coordinate rank */ rcd=nco_inq_varndims(in_id,cf->crd_id[0],&crd_rnk); if(crd_rnk != 2){ (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s has %i dimension(s). Skipping CF coordinates method.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],crd_rnk); goto skp_cf; } /* !crd_rnk */ rcd=nco_inq_vardimid(in_id,cf->crd_id[0],cf->dmn_id); cf->dmn_nm[0]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); cf->dmn_nm[1]=(char *)nco_malloc(NC_MAX_NAME*sizeof(NC_CHAR)); rcd=nco_inq_dimname(in_id,cf->dmn_id[0],cf->dmn_nm[0]); rcd=nco_inq_dimname(in_id,cf->dmn_id[1],cf->dmn_nm[1]); /* "coordinates" convention does not guarantee lat, lon are specified in that order Use "units" values, if any, to determine order In absence of "units", assume order is lat, lon */ nco_bool crd0_is_lat=False; /* [flg] First coordinate is latitude */ nco_bool crd0_is_lon=False; /* [flg] First coordinate is longitude */ nco_bool crd1_is_lat=False; /* [flg] Second coordinate is latitude */ nco_bool crd1_is_lon=False; /* [flg] Second coordinate is longitude */ if(cf->unt_sng[0]){ if(!strcasecmp(cf->unt_sng[0],"degrees_north") || !strcasecmp(cf->unt_sng[0],"degree_north") || !strcasecmp(cf->unt_sng[0],"degree_N") || !strcasecmp(cf->unt_sng[0],"degrees_N") || !strcasecmp(cf->unt_sng[0],"degreeN") || !strcasecmp(cf->unt_sng[0],"degreesN")) crd0_is_lat=True; if(!strcasecmp(cf->unt_sng[0],"degrees_east") || !strcasecmp(cf->unt_sng[0],"degree_east") || !strcasecmp(cf->unt_sng[0],"degree_E") || !strcasecmp(cf->unt_sng[0],"degrees_E") || !strcasecmp(cf->unt_sng[0],"degreeE") || !strcasecmp(cf->unt_sng[0],"degreesE")) crd0_is_lon=True; } /* endif */ if(cf->unt_sng[1]){ if(!strcasecmp(cf->unt_sng[1],"degrees_north") || !strcasecmp(cf->unt_sng[1],"degree_north") || !strcasecmp(cf->unt_sng[1],"degree_N") || !strcasecmp(cf->unt_sng[1],"degrees_N") || !strcasecmp(cf->unt_sng[1],"degreeN") || !strcasecmp(cf->unt_sng[1],"degreesN")) crd1_is_lat=True; if(!strcasecmp(cf->unt_sng[1],"degrees_east") || !strcasecmp(cf->unt_sng[1],"degree_east") || !strcasecmp(cf->unt_sng[1],"degree_E") || !strcasecmp(cf->unt_sng[1],"degrees_E") || !strcasecmp(cf->unt_sng[1],"degreeE") || !strcasecmp(cf->unt_sng[1],"degreesE")) crd1_is_lon=True; } /* endif */ assert((crd0_is_lat && crd1_is_lon) || (crd0_is_lon && crd1_is_lat)); int idx_lat; int idx_lon; if(crd0_is_lat && crd1_is_lon){ idx_lat=0; idx_lon=1; }else{ idx_lat=1; idx_lon=0; } /* endif */ /* Dimensions and coordinates have been vetted. Store as primary lookup names. Dimensions are always returned in order [LRV,MRV]=[0,1] LRV is along-track direction, and MRV is across-track (at least in NASA data) Internally we label LRV as "lat" and MRV as "lon" so that code looks similar for curvilinear and rectangular grids */ dmn_id_lat=cf->dmn_id[0]; dmn_id_lon=cf->dmn_id[1]; /* Subtlety: lat_nm_in is coordinate (variable+dimension) name when specified from command-line (as in nco_grd_nfr()), dimension name when found through CF-method (as in nco_rgr_wgt()). This confusing distinction could be avoided by passing command-line dimension names through-to nco_rgr_wgt(). However, that route would require complex priorities for what to do when passing command-line coordinate names not dimension names and visa-versa. */ //lat_nm_in=strdup(cf->dmn_nm[0]); //lon_nm_in=strdup(cf->dmn_nm[1]); lat_nm_in=strdup(cf->crd_nm[idx_lat]); lon_nm_in=strdup(cf->crd_nm[idx_lon]); /* Next four lines unnecessary in nco_rgr_wgt() which only needs dimension names (it reads input coordinates from map- not data-file) */ lat_ctr_id=cf->crd_id[idx_lat]; lon_ctr_id=cf->crd_id[idx_lon]; lat_dmn_nm=strdup(cf->dmn_nm[0]); lon_dmn_nm=strdup(cf->dmn_nm[1]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s reports coordinates variable %s \"coordinates\" attribute \"%s\" points to coordinates %s and %s. Latitude coordinate \"%s\" has LRV (along-track) and MRV (across-track) dimensions \"%s\" and \"%s\", respectively.\n",nco_prg_nm_get(),fnc_nm,rgr_var,cf->crd_sng,cf->crd_nm[0],cf->crd_nm[1],cf->crd_nm[idx_lat],cf->dmn_nm[0],cf->dmn_nm[1]); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s Coordinates %s and %s \"units\" values are \"%s\" and \"%s\", respectively.\n",nco_prg_nm_get(),fnc_nm,cf->crd_nm[0],cf->crd_nm[1],cf->unt_sng[0] ? cf->unt_sng[0] : "(non-existent)",cf->unt_sng[1] ? cf->unt_sng[1] : "(non-existent)"); /* Clean-up CF coordinates memory */ if(crd_dpl) crd_dpl=(char *)nco_free(crd_dpl); if(cf->crd_sng) cf->crd_sng=(char *)nco_free(cf->crd_sng); if(cf->dmn_nm[0]) cf->dmn_nm[0]=(char *)nco_free(cf->dmn_nm[0]); if(cf->dmn_nm[1]) cf->dmn_nm[1]=(char *)nco_free(cf->dmn_nm[1]); if(cf->unt_sng[0]) cf->unt_sng[0]=(char *)nco_free(cf->unt_sng[0]); if(cf->unt_sng[1]) cf->unt_sng[1]=(char *)nco_free(cf->unt_sng[1]); } /* !rgr_var */ /* goto skp_cf */ skp_cf: /* free() any abandoned cf structure now */ if(!flg_cf) if(cf) cf=(cf_crd_sct *)nco_free(cf); rcd=NC_NOERR; /* End CF-coordinates block */ /* Locate fields that must be present in input file Required variables are usually latitude and longitude Currently these variables must be in root group This fails for, e.g., OMI L2 which has coordinates /GEOLOCATION_DATA/[Latitude,Longitude] fxm: Generalize with traversal table so usual suspect coordinates may be in any group */ if(lat_ctr_id == NC_MIN_INT){ if(rgr->lat_nm_in && (rcd=nco_inq_varid_flg(in_id,rgr->lat_nm_in,&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup(rgr->lat_nm_in); else if((rcd=nco_inq_varid_flg(in_id,"latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("latitude"); else if((rcd=nco_inq_varid_flg(in_id,"Latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("Latitude"); /* AMSR, HIRDLS, TRMM */ else if((rcd=nco_inq_varid_flg(in_id,"lat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("lat"); /* CAM */ else if((rcd=nco_inq_varid_flg(in_id,"lat_d",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("lat_d"); /* EAM dynamics grid */ else if((rcd=nco_inq_varid_flg(in_id,"Lat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("Lat"); else if((rcd=nco_inq_varid_flg(in_id,"XLAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("XLAT"); /* WRF */ else if((rcd=nco_inq_varid_flg(in_id,"XLAT_M",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("XLAT_M"); /* Unknown */ else if((rcd=nco_inq_varid_flg(in_id,"LAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("LAT"); /* MAR/RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"LATIXY",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("LATIXY"); /* CISM/CLM/ELM */ else if((rcd=nco_inq_varid_flg(in_id,"TLAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("TLAT"); /* CICE, POP */ else if((rcd=nco_inq_varid_flg(in_id,"ULAT",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("ULAT"); /* CICE, POP */ else if((rcd=nco_inq_varid_flg(in_id,"latCell",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("latCell"); /* MPAS-O/I */ else if((rcd=nco_inq_varid_flg(in_id,"nav_lat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("nav_lat"); /* NEMO */ else if((rcd=nco_inq_varid_flg(in_id,"rlat",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("rlat"); /* RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"global_latitude0",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("global_latitude0"); /* Oxford */ else if((rcd=nco_inq_varid_flg(in_id,"latitude0",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("latitude0"); /* Oxford NB: Must search for global_* first */ else if((rcd=nco_inq_varid_flg(in_id,"CO_Latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("CO_Latitude"); /* MLS */ else if((rcd=nco_inq_varid_flg(in_id,"S1_Latitude",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("S1_Latitude"); /* GPM */ else if((rcd=nco_inq_varid_flg(in_id,"yc",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("yc"); /* RTM */ else if((rcd=nco_inq_varid_flg(in_id,"south_north",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("south_north"); /* StackOverflow question https://stackoverflow.com/questions/68896581 */ else if((rcd=nco_inq_varid_flg(in_id,"gridlat_0",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("gridlat_0"); /* NWS HRRR */ else if((rcd=nco_inq_varid_flg(in_id,"y",&lat_ctr_id)) == NC_NOERR) lat_nm_in=strdup("y"); /* Rignot (2013) */ } /* !lat_ctr_id */ if(lon_ctr_id == NC_MIN_INT){ if(rgr->lon_nm_in && (rcd=nco_inq_varid_flg(in_id,rgr->lon_nm_in,&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup(rgr->lon_nm_in); else if((rcd=nco_inq_varid_flg(in_id,"longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("longitude"); else if((rcd=nco_inq_varid_flg(in_id,"Longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("Longitude"); /* AMSR, TRMM */ else if((rcd=nco_inq_varid_flg(in_id,"lon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("lon"); /* CAM */ else if((rcd=nco_inq_varid_flg(in_id,"lon_d",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("lon"); /* EAM dynamics grid */ else if((rcd=nco_inq_varid_flg(in_id,"Lon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("Lon"); else if((rcd=nco_inq_varid_flg(in_id,"XLONG",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("XLONG"); /* WRF */ else if((rcd=nco_inq_varid_flg(in_id,"XLONG_M",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("XLONG_M"); /* Unknown */ else if((rcd=nco_inq_varid_flg(in_id,"LON",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("LON"); /* MAR/RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"LONGXY",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("LONGXY"); /* CISM/CLM/ELM */ else if((rcd=nco_inq_varid_flg(in_id,"TLON",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("TLON"); /* CICE */ else if((rcd=nco_inq_varid_flg(in_id,"TLONG",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("TLONG"); /* POP */ else if((rcd=nco_inq_varid_flg(in_id,"ULON",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("ULON"); /* CICE */ else if((rcd=nco_inq_varid_flg(in_id,"ULONG",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("ULONG"); /* POP */ else if((rcd=nco_inq_varid_flg(in_id,"lonCell",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("lonCell"); /* MPAS-O/I */ else if((rcd=nco_inq_varid_flg(in_id,"nav_lon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("nav_lon"); /* NEMO */ else if((rcd=nco_inq_varid_flg(in_id,"rlon",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("rlon"); /* RACMO */ else if((rcd=nco_inq_varid_flg(in_id,"global_longitude0",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("global_longitude0"); /* Oxford NB: Must search for global_* first */ else if((rcd=nco_inq_varid_flg(in_id,"longitude0",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("longitude0"); /* Oxford */ else if((rcd=nco_inq_varid_flg(in_id,"CO_Longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("CO_Longitude"); /* MLS */ else if((rcd=nco_inq_varid_flg(in_id,"S1_Longitude",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("S1_Longitude"); /* GPM */ else if((rcd=nco_inq_varid_flg(in_id,"xc",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("xc"); /* RTM */ else if((rcd=nco_inq_varid_flg(in_id,"west_east",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("west_east"); /* StackOverflow question https://stackoverflow.com/questions/68896581 */ else if((rcd=nco_inq_varid_flg(in_id,"gridlon_0",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("gridlon_0"); /* NWS HRRR */ else if((rcd=nco_inq_varid_flg(in_id,"x",&lon_ctr_id)) == NC_NOERR) lon_nm_in=strdup("x"); /* Rignot (2013) */ } /* !lon_ctr_id */ if(!lat_nm_in || !lon_nm_in){ (void)fprintf(stdout,"%s: ERROR %s unable to identify latitude and/or longitude variable.\nHINT: Potential causes and workarounds for this include: 1. Coordinate variables must be in the root directory (not in a group). If this might be the problem, try to \"flatten\" the input file before regridding it (see http://nco.sf.net/nco.html#flatten). 2. Horizontal dimensions with \"unusual\" names are hard to identify unless the user designates them as such. ncremap will search for horizontal dimensions named in the \"coordinates\" attribute in a template variable specified with the \"-V rgr_var\" option. 3. NCO will also search its own internal database for likely names of horizontal coordinate variables (lat, latitude, LAT, XLAT, etc.). Contact the NCO project to have your idiosyncratic coordinate names added to the internal database.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !lat_nm_in */ /* Rank of coordinates determines whether grid is curvilinear */ rcd+=nco_inq_varndims(in_id,lat_ctr_id,&lat_rnk); rcd+=nco_inq_varndims(in_id,lon_ctr_id,&lon_rnk); /* If lat_ctr and lon_ctr share same and only dimension then grid is unstructured */ if(lat_rnk*lon_rnk == 1){ rcd+=nco_inq_vardimid(in_id,lat_ctr_id,&dmn_id_lat); rcd+=nco_inq_vardimid(in_id,lon_ctr_id,&dmn_id_lon); if(dmn_id_lat == dmn_id_lon){ dmn_id_col=dmn_id_lat; dmn_id_lat=NC_MIN_INT; dmn_id_lon=NC_MIN_INT; rcd+=nco_inq_dimname(in_id,dmn_id_col,dmn_nm); col_dmn_nm=(char *)strdup(dmn_nm); flg_grd_1D=True; } /* !unstructured */ } /* lat_rnk == lon_rnk == 1 */ if(lat_rnk*lon_rnk == 1 && dmn_id_lat != NC_MIN_INT && dmn_id_lon != NC_MIN_INT){ flg_grd_crv=False; flg_grd_2D=True; } /* !lat_rnk */ if(lat_rnk == dmn_nbr_2D || lon_rnk == dmn_nbr_2D){ flg_grd_crv=True; flg_grd_2D=False; } /* !lat_rnk */ if(lat_rnk > dmn_nbr_2D || lon_rnk > dmn_nbr_2D){ (void)fprintf(stdout,"%s: ERROR %s reports an identified grid variable (%s with rank %d and/or %s with rank %d) has rank greater than two---grid variables currently must have rank 1 or 2.\nHINT: If grid variables do not vary in time, then temporally average them (with, e.g., ncwa -a time in.nc out.nc) prior to inferring grid\n",nco_prg_nm_get(),fnc_nm,lat_nm_in,lat_rnk,lon_nm_in,lon_rnk); nco_exit(EXIT_FAILURE); } /* !3D */ if(lat_rnk*lon_rnk != 1 && lat_rnk*lon_rnk != 4) assert(False); /* Scrutinize coordinates for their dimensions NB: Unstructured already known */ if(flg_grd_2D){ rcd+=nco_inq_dimname(in_id,dmn_id_lat,dmn_nm); lat_dmn_nm=(char *)strdup(dmn_nm); rcd+=nco_inq_dimname(in_id,dmn_id_lon,dmn_nm); lon_dmn_nm=(char *)strdup(dmn_nm); } /* !flg_grd_2D */ if(flg_grd_crv){ rcd+=nco_inq_vardimid(in_id,lat_ctr_id,dmn_ids); /* fxm: use cf struct and match with units name, if any? normally curvilinear grid dimensions are just pixel dimensions that are not aligned north-south or east-west */ dmn_id_lat=dmn_ids[0]; dmn_id_lon=dmn_ids[1]; rcd+=nco_inq_dimname(in_id,dmn_id_lat,dmn_nm); lat_dmn_nm=(char *)strdup(dmn_nm); rcd+=nco_inq_dimname(in_id,dmn_id_lon,dmn_nm); lon_dmn_nm=(char *)strdup(dmn_nm); } /* !flg_grd_crv */ if(!(lat_dmn_nm && lon_dmn_nm) && !col_dmn_nm){ (void)fprintf(stdout,"%s: ERROR %s unable to identify latitude and/or longitude dimension and/or column dimension.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !col_dmn_nm !lat_dmn_nm !lon_dmn_nm */ /* Locate spatial dimensions that may be present NB: bounds dimensions may present a special problem CAM-FV and CAM-SE use nbnd for temporal bounds and have no spatial bounds dimension CAM3 uses tbnd for temporal bounds and has no spatial bounds dimension CICE and POP use d2 for temporal bounds, and CICE uses nvertices for spatial bounds while POP uses nothing Hence search for nvertices before nbnd to ensure spatial bound is found first */ if((rcd=nco_inq_dimid_flg(in_id,"nv",&dmn_id_bnd)) == NC_NOERR) bnd_dmn_nm=strdup("nv"); /* fxm */ else if((rcd=nco_inq_dimid_flg(in_id,"nvertices",&dmn_id_bnd)) == NC_NOERR) bnd_dmn_nm=strdup("nvertices"); /* CICE */ else if((rcd=nco_inq_dimid_flg(in_id,"maxEdges",&dmn_id_bnd)) == NC_NOERR) bnd_dmn_nm=strdup("maxEdges"); /* MPAS */ if((rcd=nco_inq_dimid_flg(in_id,"nVertices",&dmn_id_vrt)) == NC_NOERR) vrt_dmn_nm=strdup("nVertices"); /* MPAS */ /* Use dimension IDs to get dimension sizes and grid size */ if(flg_grd_1D){ rcd+=nco_inq_dimlen(in_id,dmn_id_col,&col_nbr); lat_nbr=lon_nbr=col_nbr; }else{ rcd+=nco_inq_dimlen(in_id,dmn_id_lat,&lat_nbr); rcd+=nco_inq_dimlen(in_id,dmn_id_lon,&lon_nbr); col_nbr=NC_MIN_INT; } /* !flg_grd_1D */ if(dmn_id_bnd != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_bnd,&grd_crn_nbr); if(dmn_id_bnd != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_bnd,&bnd_nbr); if(dmn_id_vrt != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_vrt,&vrt_nbr); if(flg_grd_1D){ /* Unstructured grid (e.g., CAM-SE) */ grd_rnk_nbr=dmn_nbr_1D; grd_typ=nco_grd_2D_unk; lat_typ=nco_grd_lat_unk; lon_typ=nco_grd_lon_unk; /* 1D grids without their own boundaries are at the mercy of the weight generator */ if(dmn_id_bnd == NC_MIN_INT){ (void)fprintf(stdout,"%s: WARNING %s reports an unstructured grid without spatial boundary information. NCO can copy but not infer spatial boundaries from unstructured grids. Thus NCO will not write spatial bounds to the gridfile inferred from this input file. Instead, the weight generator that ingests this gridfile must generate weights for gridcells with unknown spatial extent. This is feasible for grids and mappings where weights masquerade as areas and are determined by underlying grid and interpolation type (e.g., bilinear remapping of spectral element grid). Unfortunately, the ESMF_RegridWeightGen (ERWG) program requires cell interfaces in both grid files, so ERWG will break on this gridfile. Other weight generators such as TempestRemap may be more successful with this SCRIP file.\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT Re-run the regridder, this time adding the \"-s src_grd\" option to specify the source grid file in SCRIP format. That SCRIP file will have the spatial bounds information required by the ESMF_RegridWeightGen (ERWG) program, so that the regridder will circumvent inferring the underlying grid through its black but fragile magic.\n",nco_prg_nm_get()); flg_wrt_crn=False; /* Input could actually be from grid with no polygonal definition, e.g., CAM-SE Corner number is non-deterministic since, e.g., CAM-SE dual grid can be fit to quadrilaterals, pentagons, chevrons, etc. Bounds will not be diagnosed so safe to set grd_crn_nbr to harmless (though weird) value like 4 However, ERWG requires presence of valid corner dimension "grid_corners" and arrays in input SCRIP file So ERWG will break when reading this SCRIP file regardless of whether it contains arrays (with bogus values) By default do not write grid corner values */ grd_crn_nbr=4; } /* !dmn_id_bnd */ if(bnd_nbr == 2){ /* Unstructured grids with bounds information (e.g., OCO2) may use a pseudo-rectangular convention of archiving latitude and longitude bounds as 2xN (rather than 4XN) arrays even though cell have four corners. "convention" is that two latitudes and two longitudes can specify rectangular boundary cell In this case, bnd_nbr=grd_crn_nbr=2=sizeof(nv)=sizeof(nvertices) currently Set number of corners to rectangular and leave bnd_nbr as is */ grd_crn_nbr=4; flg_1D_psd_rct_bnd=True; } /* !bnd_nbr */ if(!strcmp(bnd_dmn_nm,"maxEdges")){ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Unstructured grid has dimension \"%s\" which indicates an MPAS grid. Will attempt to locate other MPAS information (dimension nVertices and variables nEdgesOnCell, verticesOnCell, lonVertex, and latVertex) to construct SCRIP-compliant bounds variables...\n",nco_prg_nm_get(),bnd_dmn_nm); if((rcd=nco_inq_varid_flg(in_id,"nEdgesOnCell",&edg_nbr_cll_id)) == NC_NOERR) edg_nbr_cll_nm=strdup("nEdgesOnCell"); if((rcd=nco_inq_varid_flg(in_id,"verticesOnCell",&vrt_cll_id)) == NC_NOERR) vrt_cll_nm=strdup("verticesOnCell"); if((rcd=nco_inq_varid_flg(in_id,"lonVertex",&vrt_lon_id)) == NC_NOERR) vrt_lon_nm=strdup("lonVertex"); if((rcd=nco_inq_varid_flg(in_id,"latVertex",&vrt_lat_id)) == NC_NOERR) vrt_lat_nm=strdup("latVertex"); if(dmn_id_vrt != NC_MIN_INT) rcd+=nco_inq_dimlen(in_id,dmn_id_vrt,&vrt_nbr); if(vrt_dmn_nm && edg_nbr_cll_nm && vrt_cll_nm && vrt_lon_nm && vrt_lat_nm){ flg_1D_mpas_bnd=True; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO Found all MPAS information needed to construct SCRIP-compliant bounds variables.\n",nco_prg_nm_get()); }else{ (void)fprintf(stdout,"%s: INFO Unable to find all MPAS information needed to construct SCRIP-compliant bounds variables. Will not write bounds coordinates. This will degrade usefulness of SCRIP file for regridding schemes (e.g., conservative) that require cell boundaries.\n",nco_prg_nm_get()); (void)fprintf(stdout,"%s: HINT Often MPAS restart files contain the required bounds variables (nEdgesOnCell, verticesOnCell, lonVertex, latVertex) that normal MPAS data files lack. Try inferring the SCRIP grid from a restart or initial condition file instead of from a time-varying output dataset.\n",nco_prg_nm_get()); flg_wrt_crn=False; } /* !vrt_cll_nm */ } /* !bnd_dmn_nm */ }else if(flg_grd_2D){ /* !flg_grd_1D */ /* Assume 2D grid of uninitialized type */ grd_rnk_nbr=dmn_nbr_2D; grd_typ=nco_grd_2D_nil; lat_typ=nco_grd_lat_nil; lon_typ=nco_grd_lon_nil; /* Assume rectangular grids that do not specify otherwise use quadrilaterals */ if(dmn_id_bnd == NC_MIN_INT) grd_crn_nbr=4; /* Sometimes we infer from a 2D grid, like those produced by nco_grd_mk(), that has bounds with nv=2 This signals rectangular gridcell bounds are interfaces not vertices (to save half the space) These rectangles really have four corners so we change grd_crn_nbr (not bnd_nbr) accordingly */ if(grd_crn_nbr == 2) grd_crn_nbr=4; /* Convention is to archive only two bounds for rectangular grids (since sides are identical) Non-quadrilateral rectangular grids are untested */ if(grd_crn_nbr == 4) bnd_nbr=2; }else if(flg_grd_crv){ /* !flg_grd_2D */ /* Assume curvilinear grid (e.g., WRF) */ flg_grd_2D=False; grd_rnk_nbr=dmn_nbr_2D; grd_typ=nco_grd_2D_unk; lat_typ=nco_grd_lat_unk; lon_typ=nco_grd_lon_unk; /* Assume curvilinear grids that do not specify otherwise use quadrilaterals */ if(dmn_id_bnd == NC_MIN_INT) grd_crn_nbr=4; /* Assume quadrilaterals are, well, quadrilaterals (e.g., rhomboids) not necessarily rectangles Non-quadrilateral curvilinear grids are untested */ if(grd_crn_nbr == 4) bnd_nbr=4; else assert(False); } /* !flg_grd_crv */ /* Allocate space for output data */ if(flg_grd_1D) grd_sz_nbr=col_nbr; else grd_sz_nbr=lat_nbr*lon_nbr; dmn_sz_int=(int *)nco_malloc(grd_rnk_nbr*nco_typ_lng((nc_type)NC_INT)); area=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); msk=(int *)nco_malloc(grd_sz_nbr*nco_typ_lng((nc_type)NC_INT)); if(flg_grd_1D){ if(bnd_nbr != NC_MIN_INT) lat_bnd=(double *)nco_malloc(grd_sz_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); if(bnd_nbr != NC_MIN_INT) lon_bnd=(double *)nco_malloc(grd_sz_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); }else if(flg_grd_2D){ /* !flg_grd_1D */ lat_bnd=(double *)nco_malloc(lat_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(lat_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lon_bnd=(double *)nco_malloc(lon_nbr*bnd_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(lon_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(lon_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); }else if(flg_grd_crv){ /* !flg_grd_2D */ lat_bnd=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lat_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lat_ntf=(double *)nco_malloc((lat_nbr+1L)*nco_typ_lng(crd_typ)); lat_wgt=(double *)nco_malloc(lat_nbr*nco_typ_lng(crd_typ)); lon_bnd=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_crn=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_ctr=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); lon_ntf=(double *)nco_malloc((lon_nbr+1L)*nco_typ_lng(crd_typ)); } /* !flg_grd_crv */ grd_ctr_lat=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_ctr_lon=(double *)nco_malloc(grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lat=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); grd_crn_lon=(double *)nco_malloc(grd_crn_nbr*grd_sz_nbr*nco_typ_lng(crd_typ)); /* Locate fields that may be present in input file */ if((rcd=nco_inq_varid_flg(in_id,"lat_bnds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("lat_bnds"); else if((rcd=nco_inq_varid_flg(in_id,"latt_bounds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("latt_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"latu_bounds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("latu_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"lat_ntf",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("lat_ntf"); else if((rcd=nco_inq_varid_flg(in_id,"lat_vertices",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("lat_vertices"); else if((rcd=nco_inq_varid_flg(in_id,"latitude_bnds",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("latitude_bnds"); /* OCO2 */ else if((rcd=nco_inq_varid_flg(in_id,"LatitudeCornerpoints",&lat_bnd_id)) == NC_NOERR) lat_bnd_nm=strdup("LatitudeCornerpoints"); /* OMI */ if((rcd=nco_inq_varid_flg(in_id,"lon_bnds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lon_bnds"); else if((rcd=nco_inq_varid_flg(in_id,"lont_bounds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lont_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"lonu_bounds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lonu_bounds"); else if((rcd=nco_inq_varid_flg(in_id,"lon_ntf",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lon_ntf"); else if((rcd=nco_inq_varid_flg(in_id,"lon_vertices",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("lon_vertices"); else if((rcd=nco_inq_varid_flg(in_id,"longitude_bnds",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("longitude_bnds"); /* OCO2 */ else if((rcd=nco_inq_varid_flg(in_id,"LongitudeCornerpoints",&lon_bnd_id)) == NC_NOERR) lon_bnd_nm=strdup("LongitudeCornerpoints"); /* OMI */ if((rcd=nco_inq_varid_flg(in_id,"area",&area_id)) == NC_NOERR) area_nm_in=strdup("area"); else if((rcd=nco_inq_varid_flg(in_id,"Area",&area_id)) == NC_NOERR) area_nm_in=strdup("Area"); else if((rcd=nco_inq_varid_flg(in_id,"areaCell",&area_id)) == NC_NOERR) area_nm_in=strdup("areaCell"); /* MPAS-O/I */ else if((rcd=nco_inq_varid_flg(in_id,"grid_area",&area_id)) == NC_NOERR) area_nm_in=strdup("grid_area"); else if((rcd=nco_inq_varid_flg(in_id,"area_d",&area_id)) == NC_NOERR) area_nm_in=strdup("area_d"); /* EAM dynamics grid */ else if((rcd=nco_inq_varid_flg(in_id,"area_p",&area_id)) == NC_NOERR) area_nm_in=strdup("area_p"); /* EAM physics grid */ // else if((rcd=nco_inq_varid_flg(in_id,"aice",&area_id)) == NC_NOERR) area_nm_in=strdup("aice"); /* CICE time-dependent ice area (3D), not total gridcell area */ else if((rcd=nco_inq_varid_flg(in_id,"tarea",&area_id)) == NC_NOERR) area_nm_in=strdup("tarea"); /* CICE time-invariant state-variable gridcell area (2D) */ else if((rcd=nco_inq_varid_flg(in_id,"uarea",&area_id)) == NC_NOERR) area_nm_in=strdup("uarea"); /* CICE time-invariant dynamics variables (2D) */ msk_nm_in=rgr->msk_var; if(msk_nm_in){ if(!strcasecmp(msk_nm_in,"none")){ /* 20170814: Some variables named "*mask*" are, e.g., quality control masks not regridding masks per se */ msk_nm_in=(char *)nco_free(msk_nm_in); }else{ /* User-supplied name overrides database */ rcd=nco_inq_varid(in_id,msk_nm_in,&msk_id); } /* !msk_nm_in */ }else{ /* Otherwise search database */ if((rcd=nco_inq_varid_flg(in_id,"mask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("mask"); else if((rcd=nco_inq_varid_flg(in_id,"Mask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("Mask"); else if((rcd=nco_inq_varid_flg(in_id,"mask_b",&msk_id)) == NC_NOERR) msk_nm_in=strdup("mask_b"); else if((rcd=nco_inq_varid_flg(in_id,"grid_imask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("grid_imask"); else if((rcd=nco_inq_varid_flg(in_id,"landmask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("landmask"); /* ALM/CLM */ else if((rcd=nco_inq_varid_flg(in_id,"tmask",&msk_id)) == NC_NOERR) msk_nm_in=strdup("tmask"); /* CICE */ } /* !msk_nm_in */ /* Mask field requires special handling for non-conformant models */ if(msk_id != NC_MIN_INT){ /* 20151201: All models tested define mask as NC_INT except CICE which uses NC_FLOAT 20160111: Few observations tested define mask. Exceptions include AMSR and GHRSST. AMSR uses NC_SHORT to store bitmasks. Bitmask is 1 for missing data, and up to 128 for various quality levels of valid data. Hence, almost better to ignore AMSR mask variable. GHRSST uses NC_BYTE for its 3D "mask" bit-mask of surface-type values 1,2,4,8,16. */ rcd=nco_inq_varndims(in_id,msk_id,&msk_rnk_nbr); if(msk_rnk_nbr != grd_rnk_nbr && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports input mask variable \"%s\" is rank %d while grid is rank %ld so will use first timestep/layer to determine output mask\n",nco_prg_nm_get(),fnc_nm,msk_nm_in,msk_rnk_nbr,grd_rnk_nbr); rcd=nco_inq_vartype(in_id,msk_id,&msk_typ); msk_unn.vp=(void *)nco_malloc(grd_sz_nbr*nco_typ_lng(msk_typ)); } /* !msk */ /* All grids: Some real-world datasets violate convention that coordinates ought never have missing values CICE lists missing value for lat/lon_ctr arrays (TLAT, TLONG) and re-uses that for bounds arrays (latt_bounds, lont_bounds) that do not bother to have their own missing value attributes Without counter-example, assume has_mss_val_bnd=has_mss_val_ctr and mss_val_bnd_dbl=mss_val_ctr_dbl */ has_mss_val_bnd=has_mss_val_ctr=nco_mss_val_get_dbl(in_id,lat_ctr_id,&mss_val_ctr_dbl); char *att_val; char *area_unt=NULL; /* [sng] Dimensional units used in area */ char *ngl_unt=NULL; /* [sng] Angular units used in coordinates */ long att_sz; nc_type att_typ; nco_bool flg_area_sr=True; /* [flg] Input area is in sterradians not something weird like km2 */ nco_bool flg_crd_rdn=False; /* [flg] Input coordinates are in radians not degrees */ if(flg_grd_1D){ /* Obtain fields that must be present in unstructured input file */ dmn_srt[0]=0L; dmn_cnt[0]=col_nbr; rcd=nco_get_vara(in_id,lat_ctr_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); rcd=nco_get_vara(in_id,lon_ctr_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); /* Obtain fields that may be present in unstructured input file */ if(area_id != NC_MIN_INT) rcd=nco_get_vara(in_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); if(msk_id != NC_MIN_INT){ if(msk_rnk_nbr > grd_rnk_nbr){ /* Retrieve mask elements only from first horizontal grid, e.g., first timestep, first layer... */ for(dmn_idx=0;dmn_idx<msk_rnk_nbr-grd_rnk_nbr;dmn_idx++){ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=1L; } /* !dmn_idx */ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=col_nbr; } /* !msk_rnk_nbr */ rcd=nco_get_vara(in_id,msk_id,dmn_srt,dmn_cnt,msk_unn.vp,msk_typ); } /* !msk_id */ dmn_srt[0]=dmn_srt[1]=0L; if(flg_1D_psd_rct_bnd){ dmn_cnt[0]=col_nbr; dmn_cnt[1]=bnd_nbr; if(lat_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); if(lon_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); }else if(flg_1D_mpas_bnd){ long cll_vrt_lst_vld; /* [idx] C (0-based) index of greatest valid vertex */ edg_nbr_cll=(int *)nco_malloc(grd_sz_nbr*nco_typ_lng((nc_type)NC_INT)); vrt_cll=(int *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng((nc_type)NC_INT)); vrt_lat=(double *)nco_malloc(vrt_nbr*nco_typ_lng(crd_typ)); vrt_lon=(double *)nco_malloc(vrt_nbr*nco_typ_lng(crd_typ)); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s reports dimension sizes bnd_nbr=%ld, col_nbr=%ld, grd_crn_nbr=%ld, vrt_nbr=%ld\n",nco_prg_nm_get(),fnc_nm,bnd_nbr,col_nbr,grd_crn_nbr,vrt_nbr); dmn_cnt[0]=col_nbr; if(edg_nbr_cll_id != NC_MIN_INT) rcd=nco_get_vara(in_id,edg_nbr_cll_id,dmn_srt,dmn_cnt,edg_nbr_cll,(nc_type)NC_INT); dmn_cnt[0]=col_nbr; dmn_cnt[1]=grd_crn_nbr; if(vrt_cll_id != NC_MIN_INT) rcd=nco_get_vara(in_id,vrt_cll_id,dmn_srt,dmn_cnt,vrt_cll,(nc_type)NC_INT); dmn_cnt[0]=vrt_nbr; if(vrt_lat_id != NC_MIN_INT) rcd=nco_get_vara(in_id,vrt_lat_id,dmn_srt,dmn_cnt,vrt_lat,crd_typ); if(vrt_lon_id != NC_MIN_INT) rcd=nco_get_vara(in_id,vrt_lon_id,dmn_srt,dmn_cnt,vrt_lon,crd_typ); rcd=nco_inq_att_flg(in_id,vrt_lat_id,unt_sng,&att_typ,&att_sz); if(rcd == NC_NOERR && att_typ == NC_CHAR){ att_val=(char *)nco_malloc((att_sz+1L)*nco_typ_lng(att_typ)); rcd+=nco_get_att(in_id,vrt_lat_id,unt_sng,att_val,att_typ); /* NUL-terminate attribute before using strstr() */ att_val[att_sz]='\0'; /* Match "radian" and "radians" */ if(strstr(att_val,"radian")) flg_crd_rdn=True; if(att_val) ngl_unt=(char *)strdup(att_val); if(att_val) att_val=(char *)nco_free(att_val); } /* !rcd && att_typ */ /* 20211031: Replace inelegant homebrew algorithm with MPAS algorithm https://github.com/MPAS-Dev/pyremap/blob/master/pyremap/descriptor.py#L189-L256 */ for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ for(col_idx=0;col_idx<col_nbr;col_idx++){ idx=col_idx*grd_crn_nbr; ttl_idx=idx+crn_idx; /* 20211031: Cause empty vertices to repeat last valid vertex */ cll_vrt_lst_vld=NCO_MIN(edg_nbr_cll[col_idx]-1L,crn_idx); /* 20201220: MPAS vertex indices use Fortran-based convention---subtract one for C */ vrt_idx=vrt_cll[idx+cll_vrt_lst_vld]-1L; assert(vrt_idx >= 0 && vrt_idx < vrt_nbr); //if(vrt_idx >= vrt_nbr) (void)fprintf(stdout,"%s: WARNING %s input gridcell %ld corner %ld has extreme MPAS input verticesOnCell value %ld (maximum valid vertex = vrt_nbr-1 = %ld-1 = %ld)\n",nco_prg_nm_get(),fnc_nm,col_idx,crn_idx,vrt_idx,vrt_nbr,vrt_nbr-1); lat_crn[ttl_idx]=vrt_lat[vrt_idx]; lon_crn[ttl_idx]=vrt_lon[vrt_idx]; //(void)fprintf(stdout,"%s: DEBUG %s reports col_idx = %ld, crn_idx = %ld, ttl_idx = %ld, vrt_idx = %ld, vrt_lat = %g, vrt_lon = %g\n",nco_prg_nm_get(),fnc_nm,col_idx,crn_idx,ttl_idx,vrt_idx,vrt_lat[vrt_idx],vrt_lon[vrt_idx]); } /* !col_idx */ } /* !crn_idx */ }else{ /* !flg_1D_mpas_bnd */ dmn_cnt[0]=col_nbr; dmn_cnt[1]=grd_crn_nbr; if(lat_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_crn,crd_typ); if(lon_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_crn,crd_typ); } /* !flg_1D_psd_rct_bnd */ } /* !flg_grd_1D */ if(flg_grd_crv){ /* Obtain fields that must be present in curvilinear input file */ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; rcd=nco_get_vara(in_id,lat_ctr_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); rcd=nco_get_vara(in_id,lon_ctr_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); /* 20150923: Also input, if present in curvilinear file, corners, area, and mask area and mask are same size as lat and lon */ if(area_id != NC_MIN_INT) rcd=nco_get_vara(in_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); if(msk_id != NC_MIN_INT){ if(msk_rnk_nbr > grd_rnk_nbr){ /* Retrieve mask elements only from first horizontal grid, e.g., first timestep, first layer... */ for(dmn_idx=0;dmn_idx<msk_rnk_nbr-grd_rnk_nbr;dmn_idx++){ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=1L; } /* !dmn_idx */ dmn_srt[dmn_idx]=dmn_srt[dmn_idx+1]=0L; dmn_cnt[dmn_idx]=lat_nbr; dmn_cnt[dmn_idx+1]=lon_nbr; } /* !msk_rnk_nbr */ rcd=nco_get_vara(in_id,msk_id,dmn_srt,dmn_cnt,msk_unn.vp,msk_typ); } /* !msk_id */ /* Corners are on curvilinear corner grid Rectangular boundaries (i.e., lat_bnd=[lat_nbr,2]) DNE for curvilinear grids Read-in *_crn arrays in curvilinear grids, and *_bnd arrays for rectilinear grids Rank-ordering of corner arrays is usually lat_nbr,lon_nbr,grd_crn_nbr as produced/expected by SCRIP However some datasets, e.g., OMI DOMINO use grd_crn_nbr,lat_nbr,lon_nbr Sigh... */ dmn_srt[0]=dmn_srt[1]=dmn_srt[2]=0L; if(lat_bnd_id != NC_MIN_INT && lon_bnd_id != NC_MIN_INT){ rcd=nco_inq_vardimid(in_id,lat_bnd_id,dmn_ids); if((dmn_ids[0] == dmn_id_lat && dmn_ids[1] == dmn_id_lon) || (dmn_ids[0] == dmn_id_lon && dmn_ids[1] == dmn_id_lat)){ dmn_id_bnd=dmn_ids[2]; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=lon_nbr; dmn_cnt[2]=grd_crn_nbr; }else if((dmn_ids[1] == dmn_id_lat && dmn_ids[2] == dmn_id_lon) || (dmn_ids[1] == dmn_id_lon && dmn_ids[2] == dmn_id_lat)){ dmn_id_bnd=dmn_ids[0]; dmn_cnt[0]=grd_crn_nbr; dmn_cnt[1]=lat_nbr; dmn_cnt[2]=lon_nbr; flg_crn_grd_lat_lon=True; }else{ (void)fprintf(stdout,"%s: WARNING %s confused by dimension-ordering of latitude bounds variable \"%s\". Will ignore this bounds variable and attempt to extrapolate vertices from centers internally...\n",nco_prg_nm_get(),fnc_nm,lat_nm_in); lat_bnd_id=NC_MIN_INT; lon_bnd_id=NC_MIN_INT; } /* !dmn_ids */ rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_crn,crd_typ); rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_crn,crd_typ); if(flg_crn_grd_lat_lon){ /* Permute corner arrays from non-canonical (grd_nbr,lat_nbr,lon_nbr) to canonical (lat_nbr,lon_nbr,grd_nbr) order */ double *lat_crn_tmp=NULL; double *lon_crn_tmp=NULL; lat_crn_tmp=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); lon_crn_tmp=(double *)nco_malloc(grd_sz_nbr*grd_crn_nbr*nco_typ_lng(crd_typ)); memcpy(lat_crn_tmp,lat_crn,grd_sz_nbr*grd_crn_nbr*sizeof(double)); memcpy(lon_crn_tmp,lon_crn,grd_sz_nbr*grd_crn_nbr*sizeof(double)); for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ for(idx=0;idx<grd_sz_nbr;idx++){ lat_idx=idx/lon_nbr; lon_idx=idx%lon_nbr; /* NB: Variables differ (lat vs. lon) but indexes are identical in next two lines */ lat_crn[lat_idx*lon_nbr*grd_crn_nbr+lon_idx*grd_crn_nbr+crn_idx]=lat_crn_tmp[crn_idx*grd_sz_nbr+idx]; lon_crn[lat_idx*lon_nbr*grd_crn_nbr+lon_idx*grd_crn_nbr+crn_idx]=lon_crn_tmp[crn_idx*grd_sz_nbr+idx]; } /* !idx */ } /* !crn_idx */ if(lat_crn_tmp) lat_crn_tmp=(double *)nco_free(lat_crn_tmp); if(lon_crn_tmp) lon_crn_tmp=(double *)nco_free(lon_crn_tmp); /* In this code branch, thought to be executed only for OMI DOMINO grids, re-compute grid center arrays (known to contain missing values) as centroids of supplied grid corners */ for(idx=0;idx<grd_sz_nbr;idx++){ lat_idx=idx/lon_nbr; lon_idx=idx%lon_nbr; lat_ctr[idx]=0.25*(lat_crn[idx*grd_crn_nbr+0L]+lat_crn[idx*grd_crn_nbr+1L]+lat_crn[idx*grd_crn_nbr+2L]+lat_crn[idx*grd_crn_nbr+3L]); lon_ctr[idx]=nco_lon_crn_avg_brnch(lon_crn[idx*grd_crn_nbr+0L],lon_crn[idx*grd_crn_nbr+1L],lon_crn[idx*grd_crn_nbr+2L],lon_crn[idx*grd_crn_nbr+3L]); } /* !idx */ } /* !flg_crd_grd_lat_lon */ } /* !lat_bnd_id */ } /* !flg_grd_crv */ if(flg_grd_2D){ int lon_psn_in=1L; /* [idx] Ordinal position of longitude dimension in rectangular grid variables like area */ int lat_psn_in=0L; /* [idx] Ordinal position of latitude dimension in rectangular grid variables like area */ int tpl_id=NC_MIN_INT; /* [id] ID of template field */ /* Obtain fields that must be present in input file */ dmn_srt[0L]=0L; dmn_cnt[0L]=lat_nbr; rcd=nco_get_vara(in_id,lat_ctr_id,dmn_srt,dmn_cnt,lat_ctr,crd_typ); dmn_srt[0L]=0L; dmn_cnt[0L]=lon_nbr; rcd=nco_get_vara(in_id,lon_ctr_id,dmn_srt,dmn_cnt,lon_ctr,crd_typ); if(lat_ctr[1L] < lat_ctr[0L]) flg_s2n=False; /* Use fields that may be present in input file to override, if necessary, default lon/lat order area and mask are both suitable templates for determining input lat/lon ordering NB: Algorithm assumes area is same rank as grid, and falls-back to mask if that has same rank as grid */ if(area_id != NC_MIN_INT) tpl_id=area_id; else if(msk_id != NC_MIN_INT && msk_rnk_nbr == grd_rnk_nbr) tpl_id=msk_id; if(tpl_id != NC_MIN_INT){ int tpl_rnk_nbr; var_id=tpl_id; /* NB: Template variable rank may exceed two with --msk_[src/dst] (e.g., SST(time,lat,lon)) */ rcd=nco_inq_varndims(in_id,var_id,&tpl_rnk_nbr); rcd=nco_inq_vardimid(in_id,var_id,dmn_ids); /* fxm: Optimize discovery of lat/lon ordering */ for(dmn_idx=0;dmn_idx<grd_rnk_nbr;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_ids[dmn_idx],dmn_nm); rcd+=nco_inq_dimlen(in_id,dmn_ids[dmn_idx],&dmn_sz); if(!strcmp(dmn_nm,lat_dmn_nm)){ assert(dmn_sz == lat_nbr); assert(dmn_idx == 0); lat_psn_in=dmn_idx; } /* !lat */ if(!strcmp(dmn_nm,lon_dmn_nm)){ assert(dmn_sz == lon_nbr); assert(dmn_idx == 1); lon_psn_in=dmn_idx; } /* !lon */ } /* !dmn_idx */ } /* !tpl */ /* Obtain fields that may be present in input file */ if(area_id != NC_MIN_INT){ var_id=area_id; rcd=nco_inq_vardimid(in_id,var_id,dmn_ids); dmn_srt[lat_psn_in]=0L; dmn_cnt[lat_psn_in]=lat_nbr; dmn_srt[lon_psn_in]=0L; dmn_cnt[lon_psn_in]=lon_nbr; rcd=nco_get_vara(in_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); } /* !area */ if(msk_id != NC_MIN_INT){ var_id=msk_id; rcd=nco_inq_vardimid(in_id,var_id,dmn_ids); dmn_srt[lat_psn_in]=0L; dmn_cnt[lat_psn_in]=lat_nbr; dmn_srt[lon_psn_in]=0L; dmn_cnt[lon_psn_in]=lon_nbr; if(msk_rnk_nbr != grd_rnk_nbr){ /* Retrieve mask elements only from first horizontal grid, e.g., first timestep, first layer... */ for(dmn_idx=0;dmn_idx<msk_rnk_nbr-grd_rnk_nbr;dmn_idx++){ dmn_srt[dmn_idx]=0L; dmn_cnt[dmn_idx]=1L; } /* !dmn_idx */ dmn_srt[dmn_idx]=dmn_srt[dmn_idx+1]=0L; dmn_cnt[dmn_idx+lat_psn_in]=lat_nbr; dmn_cnt[dmn_idx+lon_psn_in]=lon_nbr; } /* !msk_rnk_nbr */ rcd=nco_get_vara(in_id,msk_id,dmn_srt,dmn_cnt,msk_unn.vp,msk_typ); } /* !msk */ /* Rectangular boundaries are often on "abbreviated" bounds grid (two bounds per center) Read-in *_crn arrays for 1D and curvilinear grids, and *_bnd arrays for rectilinear grids */ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lat_nbr; dmn_cnt[1]=bnd_nbr; if(lat_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lat_bnd_id,dmn_srt,dmn_cnt,lat_bnd,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=lon_nbr; dmn_cnt[1]=bnd_nbr; if(lon_bnd_id != NC_MIN_INT) rcd=nco_get_vara(in_id,lon_bnd_id,dmn_srt,dmn_cnt,lon_bnd,crd_typ); } /* !flg_grd_2D */ /* Obtain units, if any, of input area */ nco_bool flg_dgn_area=rgr->flg_dgn_area; /* [flg] Diagnose rather than copy inferred area */ /* 20211102 Always diagnose area from MPAS files so ERWG does not populate map-files with square kilometers */ if(flg_1D_mpas_bnd && area_id != NC_MIN_INT) flg_dgn_area=True; if(area_id != NC_MIN_INT){ rcd=nco_inq_att_flg(in_id,area_id,unt_sng,&att_typ,&att_sz); if(rcd == NC_NOERR && att_typ == NC_CHAR){ att_val=(char *)nco_malloc((att_sz+1L)*nco_typ_lng(att_typ)); rcd+=nco_get_att(in_id,area_id,unt_sng,att_val,att_typ); /* NUL-terminate attribute before using strstr() */ att_val[att_sz]='\0'; if(!strcasestr(att_val,"radian")) flg_area_sr=False; if(att_val) area_unt=(char *)strdup(att_val); if(att_val) att_val=(char *)nco_free(att_val); if(area_unt && !flg_area_sr && !flg_dgn_area) (void)fprintf(stderr,"%s: WARNING %s reports input grid area units are \"%s\", i.e., are apparently NOT steradians. This can cause downstream problems when comparing areas to steradian-based units. For example, using this grid with ESMF will lead to strange-looking results in the map-checker because ESMF-generated map-files retain the original area values by default (whereas NCO overwrites the originals with internally computed steradian values by default). To avoid these potential issues, consider explicitly specifying the --area_dgn (or synonyms --dgn_area, --diagnose_area, --area_diagnose) flag. This would cause NCO to write the diagnosed (not copied) grid_area variable in steradians to the grid-file.\n",nco_prg_nm_get(),fnc_nm,area_unt); } /* !rcd && att_typ */ } /* !area_id */ /* Additional information that may be required for any input grid */ if(area_id != NC_MIN_INT) has_mss_val_area=nco_mss_val_get_dbl(in_id,area_id,&mss_val_area_dbl); if(msk_id != NC_MIN_INT) has_mss_val_msk=nco_mss_val_get_dbl(in_id,msk_id,&mss_val_msk_dbl); /* 20160115: AMSR coordinates are packed as NC_SHORT with scale_value=0.01f. What to do? Is it worth unpacking everything? */ int flg_pck; /* [flg] Variable is packed on disk */ rcd=nco_inq_var_packing(in_id,lat_ctr_id,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports lat_ctr variable \"%s\" is packed so results unpredictable. HINT: If grid-generation causes problems, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,lat_nm_in); rcd=nco_inq_var_packing(in_id,lon_ctr_id,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports lon_ctr variable \"%s\" is packed so results unpredictable. HINT: If grid-generation causes problems, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,lon_nm_in); /* Close input netCDF file */ nco_close(in_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); /* Above this line, fl_in and in_id refer to input file to be regridded Below this line, fl_out and out_id refer to grid-file to be output */ dfl_lvl=rgr->dfl_lvl; fl_out=rgr->fl_grd; fl_out_fmt=rgr->fl_out_fmt; if(!fl_out){ (void)fprintf(stdout,"%s: ERROR %s filename for inferred SCRIP grid-file is uninitialized, supply it with \"ncks --rgr grid=filename.nc\" or \"ncremap -R '--rgr grid=filename.nc'\"\n",nco_prg_nm_get(),fnc_nm); (void)fprintf(stdout,"%s: HINT ncremap supplies an automatically generated default name for any output SCRIP grid-file. Users of the standalone regridder (ncks) must explicitly specify a name for the inferred SCRIP grid-file.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* !fl_out */ /* Define output variable values */ int lon_psn; /* [idx] Ordinal position of longitude dimension in rectangular grid dimension-size array */ int lat_psn; /* [idx] Ordinal position of latitude dimension in rectangular grid dimension-size array */ if(grd_rnk_nbr == dmn_nbr_1D){ dmn_sz_int[0]=col_nbr; }else if(grd_rnk_nbr == dmn_nbr_2D){ /* !dmn_nbr_1D */ /* SCRIP introduced [lon,lat] convention because more natural for Fortran NB: This [lon,lat] convention applies ONLY to grid_dims variable Write all other SCRIP variables as [lat,lon] Nonsensical? Yes, but backwards compatibility is priceless */ lon_psn=0; lat_psn=1; dmn_sz_int[lon_psn]=lon_nbr; dmn_sz_int[lat_psn]=lat_nbr; } /* !dmn_nbr_2D */ if(flg_grd_crv){ /* For curvilinear grids first, if necessary, infer corner boundaries Then perform sanity check using same code on inferred and copied grids */ if(False && has_mss_val_bnd && grd_crn_nbr == 4 && !strcmp(lat_bnd_nm,"latt_bounds") && !strcmp(lon_bnd_nm,"lont_bounds") && lat_bnd_id != NC_MIN_INT && lon_bnd_id != NC_MIN_INT){ /* Only CESM CICE is known to fit these constraints Cell center locations are (misleadingly) reported in a regular, rectangular, regional grid Cell corners/boundaries are regular only in SH, curvilinear in NH, i.e., displaced or tripole grid Grid is from southernmost Antarctic Ocean latitude and longitude near 79S,320E to North Pole Nominal centers do not agree with true centers computed from corners CICE may run in decomposed/unstructured mode, each column writes separately to output buffer? This could explain missing coordinates in non-ocean gridcells However, land points are completely masked (grid centers and corners are missing) Oversight? Why not write coordinates for land-masked cells? Regridder needs corners so we fill-in missing boundaries with derived grid Gave up on inferring 20170521 once tri-pole grid complexity became apparent */ const long idx_dbg=rgr->idx_dbg; double lat_ctr_drv; /* [dgr] Latitude center, derived */ double lon_ctr_drv; /* [dgr] Longitude center, derived */ double lat_crn_drv; /* [dgr] Latitude corner, derived */ double lon_crn_drv; /* [dgr] Longitude corner, derived */ long idx_ctr_sth; /* [idx] Index of southern neighbor */ long idx_ctr_nrt; /* [idx] Index of northern neighbor */ long idx_crn_sth; /* [idx] Index of southern neighbor */ long idx_crn_nrt; /* [idx] Index of northern neighbor */ long lon_idx_crr; /* [idx] Current longitude index */ long lon_vld_frs; /* [idx] First valid longitude in latitude row */ long *lon_vld_prv=NULL; /* [idx] Previous valid longitude in latitude row */ long *lon_vld_nxt=NULL; /* [idx] Next valid longitude in latitude row */ lon_vld_prv=(long *)nco_malloc(lon_nbr*sizeof(long)); lon_vld_nxt=(long *)nco_malloc(lon_nbr*sizeof(long)); /* First valid gridcell sets west and south bounds of entire grid */ for(idx_ctr=0;idx_ctr<grd_sz_nbr;idx_ctr++){ if(lat_ctr[idx_ctr] != mss_val_ctr_dbl) break; } /* !grd_sz_nbr */ assert(idx_ctr != grd_sz_nbr); idx_crn=idx_ctr*grd_crn_nbr; lat_sth=lat_crn[idx_crn]; lat_ncr=lat_crn[idx_crn+3]-lat_crn[idx_crn]; /* ul-ll */ lon_wst=lon_crn[idx_crn]; lon_ncr=lon_crn[idx_crn+1]-lon_crn[idx_crn]; /* lr-ll */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO %s will assume grid is regional CICE in curvilinear format with masked land. Will diagnose missing cell boundaries and centers from present boundaries and centers in grid of size lat_nbr=%ld, lon_nbr=%ld.\n",nco_prg_nm_get(),fnc_nm,lat_nbr,lon_nbr); for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ idx_ctr=lat_idx*lon_nbr; /* Find first valid longitude at this latitude */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++) if(lat_ctr[idx_ctr+lon_idx] != mss_val_ctr_dbl) break; lon_vld_frs=lon_idx; /* 20170519: Verified all tri-pole grid latitudes have at least one valid point */ if(lon_vld_frs == -1L) abort(); for(lon_idx_crr=0;lon_idx_crr<lon_nbr;lon_idx++){ /* Find previous and next valid longitude for all longitudes at this latitude Cells can be their own previous/next valid longitude */ lon_vld_prv[lon_idx_crr]=-1L; lon_vld_nxt[lon_idx_crr]=-1L; /* Start from current longitude and move left (west)... */ for(lon_idx=lon_idx_crr;lon_idx>=0;lon_idx--) if(lat_ctr[idx_ctr+lon_idx] != mss_val_ctr_dbl) break; if(lon_idx >= 0) lon_vld_prv[lon_idx_crr]=lon_idx; /* Start from current longitude and move right (east)... */ for(lon_idx=lon_idx_crr;lon_idx<lon_nbr;lon_idx++) if(lat_ctr[idx_ctr+lon_idx] != mss_val_ctr_dbl) break; if(lon_idx < lon_nbr) lon_vld_nxt[lon_idx_crr]=lon_idx; /* Wrap west if previous valid cell not found */ lon_vld_prv[lon_idx_crr]=lon_vld_prv[lon_nbr-1L]; /* Wrap east if next valid cell not found */ lon_vld_nxt[lon_idx_crr]=lon_vld_nxt[0]; } /* !lon_idx_crr */ /* Derive centers and corners for each missing point */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx_ctr=lat_idx*lon_nbr+lon_idx; idx_crn=idx_ctr*grd_crn_nbr; if(lat_ctr[idx_ctr] != mss_val_ctr_dbl){ lat_sth=lat_crn[idx_crn]; lat_ncr=lat_crn[idx_crn+3]-lat_crn[idx_crn]; /* ul-ll */ lat_ctr_drv=lat_sth+0.5*lat_ncr; lat_crn_drv=lat_sth; lon_wst=lon_crn[idx_crn]; lon_ncr=lon_crn[idx_crn+1]-lon_crn[idx_crn]; /* lr-ll */ lon_ctr_drv=lon_wst+lon_ncr*(lon_idx+0.5); if(nco_dbg_lvl_get() >= nco_dbg_std && idx_ctr == idx_dbg) (void)fprintf(stdout,"%s: DEBUG %s idx=%ld lat_idx=%ld, lon_idx=%ld, lat_sth=%g, lat_ncr=%g, lon_wst=%g, lon_ncr=%g\n",nco_prg_nm_get(),fnc_nm,idx_ctr,lat_idx,lon_idx,lat_sth,lat_ncr,lon_wst,lon_ncr); } /* !idx_ctr */ if(lat_ctr[idx_ctr] == mss_val_ctr_dbl){ if(lat_idx != 0L){ /* Not bottom row */ idx_ctr_sth=idx_ctr-lon_nbr; if(lat_ctr[idx_ctr_sth] != mss_val_ctr_dbl){ /* Copy southern corners from northern corners of southern neighbor */ idx_crn_sth=idx_ctr_sth*grd_crn_nbr; lat_crn[idx_crn+0L]=lat_crn[idx_crn_sth+3L]; lat_crn[idx_crn+1L]=lat_crn[idx_crn_sth+2L]; lon_crn[idx_crn+0L]=lon_crn[idx_crn_sth+3L]; lon_crn[idx_crn+1L]=lon_crn[idx_crn_sth+2L]; } /* !mss_val */ } /* !lat_idx */ if(lat_idx != lat_nbr-1L){ /* Not top row */ idx_ctr_nrt=idx_ctr+lon_nbr; if(lat_ctr[idx_ctr_nrt] != mss_val_ctr_dbl){ /* Copy northern corners from southern corners of northern neighbor */ idx_crn_nrt=idx_ctr_nrt*grd_crn_nbr; lat_crn[idx_crn+2L]=lat_crn[idx_crn_nrt+1L]; lat_crn[idx_crn+3L]=lat_crn[idx_crn_nrt+0L]; lon_crn[idx_crn+2L]=lon_crn[idx_crn_nrt+1L]; lon_crn[idx_crn+3L]=lon_crn[idx_crn_nrt+0L]; } /* !mss_val */ } /* !lat_idx */ /* Got to here before giving up Idea was to interpolate missing cell corners between previous and next valid cell */ /* Algorithm assumes lon_wst never changes (too simple for displaced/tri_pole) */ lon_ctr_drv=lon_wst+lon_ncr*(lon_idx+0.5); lon_crn_drv=lon_wst+lon_ncr*lon_idx; if(lon_ctr_drv >= 360.0) lon_ctr_drv-=360.0; lat_ctr[idx_ctr]=lat_ctr_drv; lon_ctr[idx_ctr]=lon_ctr_drv; lat_crn[idx_crn+0L]=lat_crn[idx_crn+1L]=lat_crn_drv; lat_crn[idx_crn+2L]=lat_crn[idx_crn+3L]=lat_crn_drv+lat_ncr; lon_crn[idx_crn+0L]=lon_crn[idx_crn+3L]=lon_crn_drv; lon_crn[idx_crn+1L]=lon_crn[idx_crn+2L]=lon_crn_drv+lon_ncr; /* Branch-cut rule */ if(lon_crn_drv+lon_ncr >= 360.0){ lon_crn[idx_crn+0L]=lon_crn[idx_crn+3L]=lon_crn_drv-360.0; lon_crn[idx_crn+1L]=lon_crn[idx_crn+2L]=lon_crn_drv+lon_ncr-360.0; } /* !brnch */ } /* !mss_val */ } /* !lon_idx */ } /* !lat_idx */ if(lon_vld_nxt) lon_vld_nxt=(long *)nco_free(lon_vld_nxt); if(lon_vld_prv) lon_vld_prv=(long *)nco_free(lon_vld_prv); } /* !False || !CICE */ if(lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT){ /* Interfaces (ntf) and boundaries (bnd) for curvilinear grids are ill-defined since sides need not follow latitudes nor meridians Simplest representation that contains equivalent information to interfaces/boundaries is grid corners array Diagnose grid corners from midpoints Most curvilinear data (e.g., WRF) is dimensioned lat x lon unlike SCRIP which uses lon x lat Hence we keep lat_ctr, lon_ctr, lat_crn, lon_crn with same order (likely lat x lon) as data file from which we infer grid Always use input order to write skeleton file Change that order, if necessary, to write SCRIP grid file In the interior of a curvilinear grid, nine points contribute to the four corners of a quadrilateral surrounding each center point These are the three points above the point, the three points at the same latitude, and the three points beneath the point In other words, a nine-point stencil is required to define the four corners inferred around each gridcell center It is cleanest to use this stencil only once for all cells in the "real"-grid, including those on the edges, not the interior For this to work cleanly we define an enlarged "fake"-grid where we pre-copy the values that lead to the desired extrapolation on "real"-grid edges Inspired by array-based solutions to integration of PDEs on meshes in Juri Toomre's class NB: implementation is not robust to missing value points in interior of grid. Hopefully grids have no missing values in coordinate variables, although they may have missing values in non-grid fields (e.g., mask, temperature) */ double *lat_ctr_fk; /* [dgr] Latitude grid with extrapolated boundaries necessary for 9-point template to find four grid corners for each real center */ double *lon_ctr_fk; /* [dgr] Longitude grid with extrapolated boundaries necessary for 9-point template to find four grid corners for each real center */ lat_ctr_fk=(double *)nco_malloc((lat_nbr+2)*(lon_nbr+2)*sizeof(double)); lon_ctr_fk=(double *)nco_malloc((lat_nbr+2)*(lon_nbr+2)*sizeof(double)); long int idx_rl; /* [idx] Index into real unrolled array */ long int idx_fk; /* [idx] Index into fake unrolled array */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ /* lat idx on real grid */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ /* lon idx on real grid */ idx_rl=lat_idx*lon_nbr+lon_idx; idx_fk=(lat_idx+1)*(lon_nbr+2)+lon_idx+1; /* Copy real grid to interior of fake grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]; lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]; } /* !lon */ } /* !lat */ /* Formulae to extrapolate sides and corners of fake grid are written as a starting lat/lon plus or minus adjustment Adjustment is positive-definite if grid monotonically increases in latitude and longitude from LL to UR 20160111: Use macros/functions to determine longitude adjustments that are always less than 180 This ensures all longitudes contributing to extrapolated longitude are from same branch cut */ /* Bottom row */ lat_idx=0; /* lat idx of extrapolated point on fake grid */ for(lon_idx=1;lon_idx<lon_nbr+1;lon_idx++){ /* lon idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on bottom row of fake grid */ idx_rl=lat_idx*lon_nbr+lon_idx-1; /* 1D-offset of neighboring point on bottom row of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]-(lat_ctr[idx_rl+lon_nbr]-lat_ctr[idx_rl]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]-nco_lon_dff_brnch_dgr(lon_ctr[idx_rl+lon_nbr],lon_ctr[idx_rl]); } /* !lon */ /* Top row */ lat_idx=lat_nbr+1; /* lat idx of extrapolated point on fake grid */ for(lon_idx=1;lon_idx<lon_nbr+1;lon_idx++){ /* lon idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on top row of fake grid */ idx_rl=(lat_nbr-1)*lon_nbr+lon_idx-1; /* 1D-offset of neighboring point on top row of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]+(lat_ctr[idx_rl]-lat_ctr[idx_rl-lon_nbr]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]+nco_lon_dff_brnch_dgr(lon_ctr[idx_rl],lon_ctr[idx_rl-lon_nbr]); } /* !lon */ /* Left side */ lon_idx=0; /* lon idx of extrapolated point on fake grid */ for(lat_idx=1;lat_idx<lat_nbr+1;lat_idx++){ /* lat idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on left side of fake grid */ idx_rl=(lat_idx-1)*lon_nbr+lon_idx; /* 1D-offset of neighboring point on left side of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]-(lat_ctr[idx_rl+1]-lat_ctr[idx_rl]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]-nco_lon_dff_brnch_dgr(lon_ctr[idx_rl+1],lon_ctr[idx_rl]); } /* !lat */ /* Right side */ lon_idx=lon_nbr+1; /* lon idx of extrapolated point on fake grid */ for(lat_idx=1;lat_idx<lat_nbr+1;lat_idx++){ /* lat idx of extrapolated point on fake grid */ idx_fk=lat_idx*(lon_nbr+2)+lon_idx; /* 1D-offset of extrapolated point on right side of fake grid */ idx_rl=(lat_idx-1)*lon_nbr+lon_idx-2; /* 1D-offset of neighboring point on right side of real grid */ lat_ctr_fk[idx_fk]=lat_ctr[idx_rl]+(lat_ctr[idx_rl]-lat_ctr[idx_rl-1]); lon_ctr_fk[idx_fk]=lon_ctr[idx_rl]+nco_lon_dff_brnch_dgr(lon_ctr[idx_rl],lon_ctr[idx_rl-1]); } /* !lat */ /* LL */ lat_ctr_fk[0]=lat_ctr_fk[lon_nbr+2]-(lat_ctr_fk[2*(lon_nbr+2)]-lat_ctr_fk[lon_nbr+2]); lon_ctr_fk[0]=lon_ctr_fk[1]-nco_lon_dff_brnch_dgr(lon_ctr_fk[2],lon_ctr_fk[1]); /* LR */ lat_ctr_fk[lon_nbr+1]=lat_ctr_fk[2*(lon_nbr+2)-1]-(lat_ctr_fk[3*(lon_nbr+2)-1]-lat_ctr_fk[2*(lon_nbr+2)-1]); lon_ctr_fk[lon_nbr+1]=lon_ctr_fk[lon_nbr]+nco_lon_dff_brnch_dgr(lon_ctr_fk[lon_nbr],lon_ctr_fk[lon_nbr-1]); /* UR */ lat_ctr_fk[(lat_nbr+2)*(lon_nbr+2)-1]=lat_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-1]+(lat_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-1]-lat_ctr_fk[lat_nbr*(lon_nbr+2)-1]); lon_ctr_fk[(lat_nbr+2)*(lon_nbr+2)-1]=lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-2]+nco_lon_dff_brnch_dgr(lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-2],lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)-3]); /* UL */ lat_ctr_fk[(lat_nbr+1)*(lon_nbr+2)]=lat_ctr_fk[lat_nbr*(lon_nbr+2)]+(lat_ctr_fk[lat_nbr*(lon_nbr+2)]-lat_ctr_fk[(lat_nbr-1)*(lon_nbr+2)]); lon_ctr_fk[(lat_nbr+1)*(lon_nbr+2)]=lon_ctr_fk[lat_nbr*(lon_nbr+2)+1]-nco_lon_dff_brnch_dgr(lon_ctr_fk[lat_nbr*(lon_nbr+2)+2],lon_ctr_fk[lat_nbr*(lon_nbr+2)+1]); if(nco_dbg_lvl_get() >= nco_dbg_std){ long idx_dbg; idx_dbg=rgr->idx_dbg; (void)fprintf(stderr,"%s: INFO %s idx_dbg = %li, Fake Center [lat,lon]=[%g,%g]\n",nco_prg_nm_get(),fnc_nm,idx_dbg,lat_ctr_fk[idx_dbg],lon_ctr_fk[idx_dbg]); } /* !dbg */ long int lat_idx_fk; /* [idx] Index into fake (extrapolated) latitude array */ long int lon_idx_fk; /* [idx] Index into fake (extrapolated) longitude array */ long int idx_fk_crn_ll_ctr_ll; long int idx_fk_crn_ll_ctr_lr; long int idx_fk_crn_ll_ctr_ur; long int idx_fk_crn_ll_ctr_ul; long int idx_fk_crn_lr_ctr_ll; long int idx_fk_crn_lr_ctr_lr; long int idx_fk_crn_lr_ctr_ur; long int idx_fk_crn_lr_ctr_ul; long int idx_fk_crn_ur_ctr_ll; long int idx_fk_crn_ur_ctr_lr; long int idx_fk_crn_ur_ctr_ur; long int idx_fk_crn_ur_ctr_ul; long int idx_fk_crn_ul_ctr_ll; long int idx_fk_crn_ul_ctr_lr; long int idx_fk_crn_ul_ctr_ur; long int idx_fk_crn_ul_ctr_ul; double *crn_lat; double *crn_lon; crn_lat=(double *)nco_malloc(grd_crn_nbr*sizeof(double)); crn_lon=(double *)nco_malloc(grd_crn_nbr*sizeof(double)); size_t wrn_nbr_max=20; size_t wrn_nbr=0; for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ /* 9-point template valid at all interior (non-edge) points in real grid, and at all points (including edges) in fake grid Read variables idx_crn_ll_ctr_ul as "index of upper left gridcell center that contributes to lower-left gridcell corner" Algorithms execute in counter-clockwise (CCW) direction: lower-left, lower-right, upper-right, upper-left lat_idx and lon_idx are true indices and are used to write into grd_crn_lat/lon arrays lat_idx_fk and lon_idx_fk are indices into fake arrays with extrapolated boundaries and are used to read data from fake arrays */ lon_idx_fk=lon_idx+1; lat_idx_fk=lat_idx+1; idx_rl=lat_idx*lon_nbr+lon_idx; idx_fk=lat_idx_fk*(lon_nbr+2)+lon_idx_fk; /* Determine index into fake array (valid everywhere it is applied) Comments after each equation are formula for real index (valid only at interior gridcells) */ idx_fk_crn_ll_ctr_ll=idx_fk-(lon_nbr+2)-1; // (lat_idx-1)*lon_nbr+lon_idx-1 idx_fk_crn_ll_ctr_lr=idx_fk-(lon_nbr+2); // (lat_idx-1)*lon_nbr+lon_idx idx_fk_crn_ll_ctr_ur=idx_fk; // lat_idx*lon_nbr+lon_idx idx_fk_crn_ll_ctr_ul=idx_fk-1; // lat_idx*lon_nbr+lon_idx-1; idx_fk_crn_lr_ctr_ll=idx_fk-(lon_nbr+2); // (lat_idx-1)*lon_nbr+lon_idx idx_fk_crn_lr_ctr_lr=idx_fk-(lon_nbr+2)+1; // (lat_idx-1)*lon_nbr+lon_idx+1 idx_fk_crn_lr_ctr_ur=idx_fk+1; // lat_idx*lon_nbr+lon_idx+1 idx_fk_crn_lr_ctr_ul=idx_fk; // lat_idx*lon_nbr+lon_idx; idx_fk_crn_ur_ctr_ll=idx_fk; // lat_idx*lon_nbr+lon_idx idx_fk_crn_ur_ctr_lr=idx_fk+1; // lat_idx*lon_nbr+lon_idx+1 idx_fk_crn_ur_ctr_ur=idx_fk+(lon_nbr+2)+1; // (lat_idx+1)*lon_nbr+lon_idx+1 idx_fk_crn_ur_ctr_ul=idx_fk+(lon_nbr+2); // (lat_idx+1)*lon_nbr+lon_idx; idx_fk_crn_ul_ctr_ll=idx_fk-1; // lat_idx*lon_nbr+lon_idx-1 idx_fk_crn_ul_ctr_lr=idx_fk; // lat_idx*lon_nbr+lon_idx idx_fk_crn_ul_ctr_ur=idx_fk+(lon_nbr+2); // (lat_idx+1)*lon_nbr+lon_idx idx_fk_crn_ul_ctr_ul=idx_fk+(lon_nbr+2)-1; // (lat_idx+1)*lon_nbr+lon_idx-1; /* 20160111: Algorithm requires that all longitudes in template be on same "branch cut" If, say, LL longitude is 179.0 and LR longitude is -179.0 then their sum and average are zero, not 180.0 or -180.0 as desired Routines labeled "*_brnch" in the following ensure that branch-cut rules are followed */ idx_crn_ll=grd_crn_nbr*idx_rl+0; lat_crn[idx_crn_ll]=0.25*(lat_ctr_fk[idx_fk_crn_ll_ctr_ll]+lat_ctr_fk[idx_fk_crn_ll_ctr_lr]+lat_ctr_fk[idx_fk_crn_ll_ctr_ur]+lat_ctr_fk[idx_fk_crn_ll_ctr_ul]); lon_crn[idx_crn_ll]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_ll_ctr_ll],lon_ctr_fk[idx_fk_crn_ll_ctr_lr],lon_ctr_fk[idx_fk_crn_ll_ctr_ur],lon_ctr_fk[idx_fk_crn_ll_ctr_ul]); idx_crn_lr=grd_crn_nbr*idx_rl+1; lat_crn[idx_crn_lr]=0.25*(lat_ctr_fk[idx_fk_crn_lr_ctr_ll]+lat_ctr_fk[idx_fk_crn_lr_ctr_lr]+lat_ctr_fk[idx_fk_crn_lr_ctr_ur]+lat_ctr_fk[idx_fk_crn_lr_ctr_ul]); lon_crn[idx_crn_lr]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_lr_ctr_ll],lon_ctr_fk[idx_fk_crn_lr_ctr_lr],lon_ctr_fk[idx_fk_crn_lr_ctr_ur],lon_ctr_fk[idx_fk_crn_lr_ctr_ul]); idx_crn_ur=grd_crn_nbr*idx_rl+2; lat_crn[idx_crn_ur]=0.25*(lat_ctr_fk[idx_fk_crn_ur_ctr_ll]+lat_ctr_fk[idx_fk_crn_ur_ctr_lr]+lat_ctr_fk[idx_fk_crn_ur_ctr_ur]+lat_ctr_fk[idx_fk_crn_ur_ctr_ul]); lon_crn[idx_crn_ur]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_ur_ctr_ll],lon_ctr_fk[idx_fk_crn_ur_ctr_lr],lon_ctr_fk[idx_fk_crn_ur_ctr_ur],lon_ctr_fk[idx_fk_crn_ur_ctr_ul]); idx_crn_ul=grd_crn_nbr*idx_rl+3; lat_crn[idx_crn_ul]=0.25*(lat_ctr_fk[idx_fk_crn_ul_ctr_ll]+lat_ctr_fk[idx_fk_crn_ul_ctr_lr]+lat_ctr_fk[idx_fk_crn_ul_ctr_ur]+lat_ctr_fk[idx_fk_crn_ul_ctr_ul]); lon_crn[idx_crn_ul]=nco_lon_crn_avg_brnch(lon_ctr_fk[idx_fk_crn_ul_ctr_ll],lon_ctr_fk[idx_fk_crn_ul_ctr_lr],lon_ctr_fk[idx_fk_crn_ul_ctr_ur],lon_ctr_fk[idx_fk_crn_ul_ctr_ul]); crn_lat[0]=lat_crn[idx_crn_ll]; crn_lat[1]=lat_crn[idx_crn_lr]; crn_lat[2]=lat_crn[idx_crn_ur]; crn_lat[3]=lat_crn[idx_crn_ul]; crn_lon[0]=lon_crn[idx_crn_ll]; crn_lon[1]=lon_crn[idx_crn_lr]; crn_lon[2]=lon_crn[idx_crn_ur]; crn_lon[3]=lon_crn[idx_crn_ul]; /* 20210411: From 2016 until today, nco_ccw_chk() overwrote fourth (UL) with first (LL) corner */ flg_ccw=nco_ccw_chk(crn_lat,crn_lon,grd_crn_nbr,idx_ccw,rcr_lvl); if(!flg_ccw && wrn_nbr < wrn_nbr_max){ (void)fprintf(stdout,"%s: %s WARNING reports non-CCW gridcell at idx=%li, (lat,lon)_idx=(%li,%li), (lat,lon) = (%g, %g)\n",nco_prg_nm_get(),fnc_nm,idx_rl,lat_idx,lon_idx,lat_ctr[lat_idx],lon_ctr[lon_idx]); wrn_nbr++; if(wrn_nbr == wrn_nbr_max) (void)fprintf(stdout,"%s: %s INFO Number of non-CCW errors reached maximum = %li, not printing anymore\n",nco_prg_nm_get(),fnc_nm,wrn_nbr_max); } /* endif */ lat_crn[idx_crn_ll]=crn_lat[0]; lat_crn[idx_crn_lr]=crn_lat[1]; lat_crn[idx_crn_ur]=crn_lat[2]; lat_crn[idx_crn_ul]=crn_lat[3]; lon_crn[idx_crn_ll]=crn_lon[0]; lon_crn[idx_crn_lr]=crn_lon[1]; lon_crn[idx_crn_ur]=crn_lon[2]; lon_crn[idx_crn_ul]=crn_lon[3]; } /* !lon */ } /* !lat */ if(lat_ctr_fk) lat_ctr_fk=(double *)nco_free(lat_ctr_fk); if(lon_ctr_fk) lon_ctr_fk=(double *)nco_free(lon_ctr_fk); if(crn_lon) crn_lon=(double *)nco_free(crn_lon); if(crn_lat) crn_lat=(double *)nco_free(crn_lat); } /* !(lat_bnd_id && lon_bnd_id) */ } /* !flg_grd_crv */ if(flg_1D_psd_rct_bnd){ double lon_brnch_min; double lon_brnch_max; double lon_dff; assert(grd_crn_nbr == 4); /* Make boundaries that were provided as pseudo-rectangular branch-cut-compliant */ for(col_idx=0;col_idx<col_nbr;col_idx++){ lon_brnch_min=(lon_bnd[2*col_idx] <= lon_bnd[2*col_idx+1]) ? lon_bnd[2*col_idx] : lon_bnd[2*col_idx+1]; lon_brnch_max=(lon_bnd[2*col_idx] >= lon_bnd[2*col_idx+1]) ? lon_bnd[2*col_idx] : lon_bnd[2*col_idx+1]; lon_dff=lon_brnch_max-lon_brnch_min; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports 1D pseudo-rectangular bounds branch-cut straddle at col_idx=%ld lon_brnch_max, lon_brnch_min, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,col_idx,lon_brnch_max,lon_brnch_min,lon_dff); lon_brnch_max-=360.0; }else if(lon_dff <= -180.0){ lon_brnch_max+=360.0; } /* !lon_dff */ /* Extra condition to convert CW bounds to CCW bounds (necessary for OCO2) */ if(lon_brnch_min <= lon_brnch_max){ lon_bnd[2*col_idx]=lon_brnch_min; lon_bnd[2*col_idx+1]=lon_brnch_max; }else{ lon_bnd[2*col_idx]=lon_brnch_max; lon_bnd[2*col_idx+1]=lon_brnch_min; } /* end else */ } /* !col_idx */ /* Convert boundaries that were provided as pseudo-rectangular to corners */ for(col_idx=0;col_idx<col_nbr;col_idx++){ idx=grd_crn_nbr*col_idx; /* fxm: OCO2 provides boundaries in CW not CCW orientation */ lon_crn[idx]=lon_bnd[2*col_idx]; /* LL */ lon_crn[idx+1]=lon_bnd[2*col_idx+1]; /* LR */ lon_crn[idx+2]=lon_bnd[2*col_idx+1]; /* UR */ lon_crn[idx+3]=lon_bnd[2*col_idx]; /* UL */ lat_crn[idx]=lat_bnd[2*col_idx]; /* LL */ lat_crn[idx+1]=lat_bnd[2*col_idx]; /* LR */ lat_crn[idx+2]=lat_bnd[2*col_idx+1]; /* UR */ lat_crn[idx+3]=lat_bnd[2*col_idx+1]; /* UL */ /* fxm: OCO2 provides boundaries in CW not CCW orientation */ } /* !col_idx */ } /* flg_1D_psd_rct_bnd */ if(flg_grd_crv || flg_1D_psd_rct_bnd){ /* As of 20160308, use same sanity check for 1D pseudo-rectangular grids as for curvilinear grids Pseudo-rectangular grids rely on user-produced boundaries that may be psychotic (CW, non-branch-cut) Starting 20151205, use same sanity check for both inferred and copied curvilinear grids 20151129: Curvilinear extrapolation technique above yields corners outside [-90.0,90.0], [-180.0,360.0] Also, it may assume input is ascending swath and fail for descending swaths Complications not fully addressed: Swaths may (verify this) turn from ascending to descending, or visa-versa, when satellite crosses latitude extrema Swaths may cross the date-line (and back!) */ /* Determine numeric bounds of input coordinate system */ double lon_min_min; double lon_max_max; nco_bool NCO_LON_0_TO_360=True; if(has_mss_val_ctr){ for(idx=0;idx<grd_sz_nbr;idx++) if(lon_ctr[idx] != mss_val_ctr_dbl && lon_ctr[idx] < 0.0) break; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(lon_ctr[idx] < 0.0) break; } /* !has_mss_val_ctr */ if(idx != grd_sz_nbr) NCO_LON_0_TO_360=False; if(NCO_LON_0_TO_360){ lon_min_min=0.0; lon_max_max=360.0; }else{ lon_min_min=-180.0; lon_max_max=180.0; } /* !NCO_LON_0_TO_360 */ /* Correct for extrapolation outside boundaries */ for(idx=0;idx<grd_sz_nbr*grd_crn_nbr;idx++){ idx_ctr=idx/grd_crn_nbr; if(has_mss_val_ctr) if(lat_ctr[idx_ctr] == mss_val_ctr_dbl) continue; if(lat_crn[idx] < -90.0 || lat_crn[idx] > 90.0 || lon_crn[idx] < lon_min_min || lon_crn[idx] > lon_max_max){ idx_crn_ll=grd_crn_nbr*idx_ctr+0; idx_crn_lr=grd_crn_nbr*idx_ctr+1; idx_crn_ur=grd_crn_nbr*idx_ctr+2; idx_crn_ul=grd_crn_nbr*idx_ctr+3; if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stderr,"%s: INFO %s reports %s corner outside canonical bounds at idx = %li, Center [lat,lon]=[%g,%g]; Corners LL [%g,%g] LR [%g,%g] UR [%g,%g] UL [%g,%g]\n",nco_prg_nm_get(),fnc_nm,(lat_bnd_id == NC_MIN_INT) ? "inferred" : "copied",idx_ctr,lat_ctr[idx_ctr],lon_ctr[idx_ctr],lat_crn[idx_crn_ll],lon_crn[idx_crn_ll],lat_crn[idx_crn_lr],lon_crn[idx_crn_lr],lat_crn[idx_crn_ur],lon_crn[idx_crn_ur],lat_crn[idx_crn_ul],lon_crn[idx_crn_ul]); /* Restrict grid to real latitudes and to the 360-degree range detected from input cell-centers */ if(lat_crn[idx] < -90.0) lat_crn[idx]=-90.0; if(lat_crn[idx] > 90.0) lat_crn[idx]=90.0; if(lon_crn[idx] < lon_min_min) lon_crn[idx]+=360.0; if(lon_crn[idx] > lon_max_max) lon_crn[idx]-=360.0; } /* !sanity */ } /* !idx */ /* Vertices (for valid points) are now within 360 degrees (either [0,360] or [-180,180]) implied by input coordinate system Curvilinear inferred grid are, by construction, branch-cut compliant fxm: Curvilinear and 1D pseudo-rectangular grids prescribed by (i.e., read-in from) input may not be branch-cut compliant */ if(nco_dbg_lvl_get() >= nco_dbg_std){ long idx_dbg; idx_dbg=rgr->idx_dbg; idx_crn_ll=grd_crn_nbr*idx_dbg+0; idx_crn_lr=grd_crn_nbr*idx_dbg+1; idx_crn_ur=grd_crn_nbr*idx_dbg+2; idx_crn_ul=grd_crn_nbr*idx_dbg+3; (void)fprintf(stderr,"%s: INFO %s idx_dbg = %li, Center [lat,lon]=[%g,%g]; Corners LL [%g,%g] LR [%g,%g] UR [%g,%g] UL [%g,%g]\n",nco_prg_nm_get(),fnc_nm,idx_dbg,lat_ctr[idx_dbg],lon_ctr[idx_dbg],lat_crn[idx_crn_ll],lon_crn[idx_crn_ll],lat_crn[idx_crn_lr],lon_crn[idx_crn_lr],lat_crn[idx_crn_ur],lon_crn[idx_crn_ur],lat_crn[idx_crn_ul],lon_crn[idx_crn_ul]); } /* !dbg */ } /* !flg_grd_crv || flg_1D_psd_rct_bnd */ if(flg_grd_crv){ /* Copy centers into empty output array */ for(idx=0;idx<grd_sz_nbr;idx++){ grd_ctr_lat[idx]=lat_ctr[idx]; grd_ctr_lon[idx]=lon_ctr[idx]; } /* !idx */ /* Copy inferred or copied (from input) sanity-checked corners into empty output array */ for(idx=0;idx<grd_sz_nbr*grd_crn_nbr;idx++){ grd_crn_lat[idx]=lat_crn[idx]; grd_crn_lon[idx]=lon_crn[idx]; } /* !idx */ } /* !flg_grd_crv */ /* 20150512 Many 2D datasets have bad bounds Primary example is Gaussian grids archived by CESM models that use midpoint rule rather than iterate to compute interfaces from quadrature points Such files have correct gw arrays and incorrect cell bounds flg_dgn_bnd allows nco_grd_nfr() to override faulty boundaries in file with correct bounds */ const nco_bool flg_dgn_bnd=rgr->flg_dgn_bnd; /* [flg] Diagnose rather than copy inferred bounds */ const long lat_nbr_hlf=lat_nbr/2L; // [nbr] Half number of latitudes (e.g., lat_nbr_hlf=32 for lat_nbr=64 and 65) if(flg_grd_2D){ if(flg_dgn_bnd || (lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT)){ if(nco_dbg_lvl_get() >= nco_dbg_std && flg_dgn_bnd) (void)fprintf(stdout,"%s: INFO %s will diagnose cell boundaries from cell centers...\n",nco_prg_nm_get(),fnc_nm); /* Derive interfaces (ntf) and bounds (bnd) from midpoints approximation applied to center data NB: Simplistically derived interfaces (ntf) only valid on some rectangular grids (not on Gaussian grids) These inferred-from-midpoint interfaces/bounds are overwritten in next block once lat grid is known */ if(flg_s2n) lat_ntf[0L]=lat_ctr[0L]-0.5*(lat_ctr[1L]-lat_ctr[0L]); else lat_ntf[0L]=lat_ctr[0L]+0.5*(lat_ctr[0L]-lat_ctr[1L]); if(lat_ntf[0L] < -90.0) lat_ntf[0L]=-90.0; /* NB: lat_ntf[0] can be same as lat_ctr[0] for cap grid */ if(lat_ntf[0L] > 90.0) lat_ntf[0L]=90.0; for(lat_idx=0L;lat_idx<lat_nbr-1L;lat_idx++) lat_ntf[lat_idx+1L]=0.5*(lat_ctr[lat_idx]+lat_ctr[lat_idx+1L]); if(flg_s2n) lat_ntf[lat_nbr]=lat_ctr[lat_nbr-1L]+0.5*(lat_ctr[lat_nbr-1L]-lat_ctr[lat_nbr-2L]); else lat_ntf[lat_nbr]=lat_ctr[lat_nbr-1L]-0.5*(lat_ctr[lat_nbr-2L]-lat_ctr[lat_nbr-1L]); if(lat_ntf[lat_nbr] > 90.0) lat_ntf[lat_nbr]=90.0; /* NB: lat_ntf[lat_nbr] can be same as lat_ctr[lat_nbr-1] for cap grid */ if(lat_ntf[lat_nbr] < -90.0) lat_ntf[lat_nbr]=-90.0; /* NB: lat_ntf[lat_nbr] can be same as lat_ctr[lat_nbr-1] for cap grid */ if(flg_s2n) lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); /* fabs() ensures positive-definite span for N->S grids */ lon_ntf[0L]=lon_ctr[0L]-0.5*(lon_ctr[1L]-lon_ctr[0L]); for(lon_idx=0;lon_idx<lon_nbr-1L;lon_idx++) lon_ntf[lon_idx+1L]=0.5*(lon_ctr[lon_idx]+lon_ctr[lon_idx+1L]); lon_ntf[lon_nbr]=lon_ctr[lon_nbr-1L]+0.5*(lon_ctr[lon_nbr-1L]-lon_ctr[lon_nbr-2L]); lon_spn=lon_ntf[lon_nbr]-lon_ntf[0L]; for(idx=0;idx<lon_nbr;idx++){ lon_bnd[2L*idx]=lon_ntf[idx]; lon_bnd[2L*idx+1L]=lon_ntf[idx+1L]; } /* !idx */ for(idx=0;idx<lat_nbr;idx++){ lat_bnd[2L*idx]=lat_ntf[idx]; lat_bnd[2L*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ }else{ /* !(lat_bnd_id && lon_bnd_id) */ /* Derive interfaces (ntf) from bounds (bnd) data on disk */ for(idx=0;idx<lon_nbr;idx++) lon_ntf[idx]=lon_bnd[2L*idx]; lon_ntf[lon_nbr]=lon_bnd[2L*lon_nbr-1L]; for(idx=0;idx<lat_nbr;idx++) lat_ntf[idx]=lat_bnd[2L*idx]; lat_ntf[lat_nbr]=lat_bnd[2L*lat_nbr-1L]; lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); /* fabs() ensures positive-definite span for N->S grids */ lon_spn=lon_ntf[lon_nbr]-lon_ntf[0L]; } /* !(lat_bnd_id && lon_bnd_id) */ } /* !flg_grd_2D */ if(flg_grd_2D){ /* Diagnose type of two-dimensional input grid by testing second latitude center against formulae */ double lat_ctr_tst_eqa; double lat_ctr_tst_fv; if(flg_s2n) lat_ctr_tst_eqa=lat_ntf[0L]+lat_spn*1.5/lat_nbr; else lat_ctr_tst_eqa=lat_ntf[0L]-lat_spn*1.5/lat_nbr; if(flg_s2n) lat_ctr_tst_fv=lat_ntf[0L]+lat_spn/(lat_nbr-1L); else lat_ctr_tst_fv=lat_ntf[0L]-lat_spn/(lat_nbr-1L); double lat_ctr_tst_gss; /* In diagnosing grids, agreement with input to single-precision is "good enough for government work" Hence some comparisons cast from double to float before comparison 20150526: T42 grid from SCRIP and related maps are only accurate to ~eight digits 20150611: map_ne120np4_to_fv801x1600_bilin.150418.nc has yc_b[1600]=-89.775000006 not expected exact value lat_ctr[1]=-89.775000000000006 20170521: T62 grid from NCEP-NCAR Reanalysis 1 worse than single precision, has yc_[192]=-86.6531 not expected exact value lat_ctr[1]=-86.6531671712612, relative difference is 7.86021e-07 20191008: T62 grid from NCEP-NCAR Reanalysis 2 worse than single precision, has yc_[92]=-86.6531 not expected exact value lat_ctr[1]=-86.6531671712612, relative difference is 7.86021e-07 */ if(nco_dbg_lvl_get() >= nco_dbg_scl && !flg_s2n) (void)fprintf(stderr,"%s: INFO %s reports that grid inferral has detected a 2D grid that runs from north-to-south, not south-to-north. Support for creating/inferring 2D N-to-S grids was added in NCO 4.7.7 (September, 2018) and should work fine.\nHINT: If present command fails, report problem to developers and then re-try inferring grid after reversing input dataset's latitude coordinate (with, e.g., ncpdq -a time,-lat,lon in.nc out.nc)\n",nco_prg_nm_get(),fnc_nm); if((float)lat_ctr[1L] == (float)lat_ctr_tst_eqa) lat_typ=nco_grd_lat_eqa; if((float)lat_ctr[1L] == (float)lat_ctr_tst_fv) lat_typ=nco_grd_lat_fv; double *lat_sin=NULL_CEWI; // [frc] Sine of Gaussian latitudes double precision double *wgt_Gss=NULL; // [frc] Gaussian weights double precision if(lat_typ == nco_grd_lat_nil){ /* Check for Gaussian grid */ lat_sin=(double *)nco_malloc(lat_nbr*sizeof(double)); wgt_Gss=(double *)nco_malloc(lat_nbr*sizeof(double)); (void)nco_lat_wgt_gss(lat_nbr,flg_s2n,lat_sin,wgt_Gss); lat_ctr_tst_gss=rdn2dgr*asin(lat_sin[1L]); /* Gaussian weights on output grid will be double-precision accurate Grid itself is kept as user-specified so area diagnosed by ESMF_RegridWeightGen may be slightly inconsistent with weights */ const double eps_rlt_cnv_gss=1.0e-6; // Convergence criterion (1.0e-7 fails for NCEP NCAR Reanalysis 1!) if(nco_dbg_lvl_get() >= nco_dbg_scl) (void)fprintf(stdout,"%s: DEBUG %s reports lat_ctr[1]=%g, lat_ctr_tst_gss=%g, fabs(1.0-fabs(lat_ctr[1]/lat_ctr_tst_gss))=%g\n",nco_prg_nm_get(),fnc_nm,lat_ctr[1],lat_ctr_tst_gss,fabs(1.0-fabs(lat_ctr[1]/lat_ctr_tst_gss))); if(fabs(1.0-fabs(lat_ctr[1]/lat_ctr_tst_gss)) < eps_rlt_cnv_gss) lat_typ=nco_grd_lat_gss; } /* !Gaussian */ if(lat_typ == nco_grd_lat_nil){ /* If still of unknown type, this 2D grid may be weird This occurs, e.g., with POP3 destination grid Change gridtype from nil (which means not-yet-set) to unknown (which means none of the others matched) */ lat_typ=nco_grd_lat_unk; } /* !nil */ /* Currently grd_lat_typ and grd_2D_typ are equivalent, though that may be relaxed in future */ if(lat_typ == nco_grd_lat_unk) grd_typ=nco_grd_2D_unk; else if(lat_typ == nco_grd_lat_gss) grd_typ=nco_grd_2D_gss; else if(lat_typ == nco_grd_lat_fv) grd_typ=nco_grd_2D_fv; else if(lat_typ == nco_grd_lat_eqa) grd_typ=nco_grd_2D_eqa; else assert(False); /* Diagnose latitude interfaces from gridcell centers (if boundaries not provided) */ if(flg_dgn_bnd || (lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT)){ //if(flg_s2n) lat_nrt=lat_ntf[lat_nbr]; else lat_nrt=lat_ntf[0L]; lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); switch(lat_typ){ case nco_grd_lat_fv: lat_ncr=lat_spn/(lat_nbr-1L); if(flg_s2n) lat_ntf[1L]=lat_ntf[0L]+0.5*lat_ncr; else lat_ntf[1L]=lat_ntf[0L]-0.5*lat_ncr; for(lat_idx=2;lat_idx<lat_nbr;lat_idx++) if(flg_s2n) lat_ntf[lat_idx]=lat_ntf[1L]+(lat_idx-1L)*lat_ncr; else lat_ntf[lat_idx]=lat_ntf[1L]-(lat_idx-1L)*lat_ncr; break; case nco_grd_lat_eqa: lat_ncr=lat_spn/lat_nbr; for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) if(flg_s2n) lat_ntf[lat_idx]=lat_ntf[0L]+lat_idx*lat_ncr; else lat_ntf[lat_idx]=lat_ntf[0L]-lat_idx*lat_ncr; break; case nco_grd_lat_gss: for(lat_idx=0L;lat_idx<lat_nbr;lat_idx++) lat_ctr[lat_idx]=rdn2dgr*asin(lat_sin[lat_idx]); /* First guess for lat_ntf is midway between Gaussian abscissae */ for(lat_idx=1L;lat_idx<lat_nbr;lat_idx++) lat_ntf[lat_idx]=0.5*(lat_ctr[lat_idx-1L]+lat_ctr[lat_idx]); /* Iterate guess until area between interfaces matches Gaussian weight */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++){ double fofx_at_x0; /* [frc] Function to iterate evaluated at current guess */ double dfdx_at_x0; /* [frc] Derivative of equation evaluated at current guess */ // 20190531: Wuyin Lin reports this convergence criterion fails on ECMWF F640 grid // Probably because latitude iterations assume s2n grid and ECMWF is n2s // Possibly also because latitude coordinates are stored in single precision // Implement precision-dependent convergence criterion, e.g., 1.0e-15 and 1.0e-7 for double- and single-precision, respectively? const double eps_rlt_cnv=1.0e-15; // Convergence criterion (1.0e-16 pushes double precision to the brink) itr_cnt=0; lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; while(fabs(fofx_at_x0) > eps_rlt_cnv){ /* Newton-Raphson iteration: Let x=lat_ntf[lat_idx], y0=lat_ntf[lat_idx-1], gw = Gaussian weight (exact solution) f(x)=sin(dgr2rdn*x)-sin(dgr2rdn*y0)-gw=0 # s2n grid f(x)=sin(dgr2rdn*y0)-sin(dgr2rdn*x)-gw=0 # n2s grid dfdx(x)= dgr2rdn*cos(dgr2rdn*x) # s2n grid dfdx(x)=-dgr2rdn*cos(dgr2rdn*x) # n2s grid x_better=x0-f(x0)/f'(x0) */ dfdx_at_x0=dgr2rdn*cos(dgr2rdn*lat_ntf[lat_idx]); if(!flg_s2n) dfdx_at_x0=-dfdx_at_x0; lat_ntf[lat_idx]+=fofx_at_x0/dfdx_at_x0; /* NB: not sure why this is minus not plus but it works :) */ lat_wgt_gss=fabs(sin(dgr2rdn*lat_ntf[lat_idx])-sin(dgr2rdn*lat_ntf[lat_idx-1L])); fofx_at_x0=wgt_Gss[lat_idx-1L]-lat_wgt_gss; if(++itr_cnt > itr_nbr_max){ (void)fprintf(stdout,"%s: ERROR %s reports convergence only %g after %d iterations for lat_idx = %ld\n",nco_prg_nm_get(),fnc_nm,fabs(fofx_at_x0),itr_nbr_max,lat_idx); nco_exit(EXIT_FAILURE); } /* endif */ } /* !while */ } /* !lat_idx */ /* Use Gaussian grid symmetry to obtain same interfaces in both hemispheres (avoids cumulative rounding errors) */ if(lat_nbr%2){ /* lat_nbr is odd */ for(lat_idx=1L;lat_idx<=lat_nbr_hlf+1L;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx+1L]; }else{ /* lat_nbr is even */ for(lat_idx=1L;lat_idx<lat_nbr_hlf;lat_idx++) lat_ntf[lat_nbr_hlf+lat_idx]=-lat_ntf[lat_nbr_hlf-lat_idx]; } /* !flg_lat_evn */ if(lat_sin) lat_sin=(double *)nco_free(lat_sin); break; case nco_grd_lat_unk: /* No generic formula exists so use interfaces already read or diagnosed as midpoints between centers */ break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ if(lat_typ == nco_grd_lat_gss){ /* 20170510: First approximation above to exterior interfaces for Gaussian grid are ~ +/-89 degrees Loops below recompute interior interfaces only Southern- and northern-most interfaces must be explicitly assigned Inferral test for Gaussian grid _assumes_ global grid Hence WLOG can assign [-90.0, 90.0] to Gaussian grid exterior boundaries */ if(flg_s2n) lat_ntf[0L]=-90.0; else lat_ntf[0L]=90.0; if(flg_s2n) lat_ntf[lat_nbr]=90.0; else lat_ntf[lat_nbr]=-90.0; } /* !nco_grd_lat_gss */ /* Now that final latitude interfaces are known for all grid-types, assign to boundaries, overwriting provisional values stored there earlier */ for(idx=0;idx<lat_nbr;idx++){ lat_bnd[2L*idx]=lat_ntf[idx]; lat_bnd[2L*idx+1L]=lat_ntf[idx+1L]; } /* !idx */ } /* !(lat_bnd_id && lon_bnd_id) */ /* Use centers and boundaries to diagnose latitude weights */ switch(lat_typ){ case nco_grd_lat_eqa: case nco_grd_lat_fv: for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=fabs(sin(dgr2rdn*lat_ntf[lat_idx+1L])-sin(dgr2rdn*lat_ntf[lat_idx])); break; case nco_grd_lat_gss: for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=wgt_Gss[lat_idx]; break; case nco_grd_lat_unk: for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt[lat_idx]=fabs(sin(dgr2rdn*lat_ntf[lat_idx+1L])-sin(dgr2rdn*lat_ntf[lat_idx])); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: WARNING %s reports unknown input latitude grid-type. Guessing that weights for grid of rectangles is OK.\n",nco_prg_nm_get(),fnc_nm); break; default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ /* Diagnose type of longitude grid by testing second longitude center against formulae */ lon_spn=lon_ntf[lon_nbr]-lon_ntf[0L]; lat_spn=fabs(lat_ntf[lat_nbr]-lat_ntf[0L]); if((float)lon_spn == 360.0f && (float)lat_spn == 180.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; if(lon_typ == nco_grd_lon_nil){ if( (float)lon_ctr[0L] == 0.0f && (float)lon_ctr[1L] == (float)(lon_ctr[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_Grn_ctr; else if((float)lon_ctr[0L] == -180.0f && (float)lon_ctr[1L] == (float)(lon_ctr[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_180_ctr; else if((float)lon_ntf[0L] == 0.0f && (float)lon_ntf[1L] == (float)(lon_ntf[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_Grn_wst; else if((float)lon_ntf[0L] == -180.0f && (float)lon_ntf[1L] == (float)(lon_ntf[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_180_wst; else if((float)lon_ctr[1L] == (float)(lon_ctr[0L]+lon_spn/lon_nbr)) lon_typ=nco_grd_lon_bb; else lon_typ=nco_grd_lon_unk; } /* !lon_typ */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input 2D grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_2D_sng(grd_typ)); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input latitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lat_sng(lat_typ)); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input longitude grid-type: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_lon_sng(lon_typ)); } /* !flg_grd_2D */ if(flg_grd_2D){ if(nco_dbg_lvl_get() >= nco_dbg_crr){ for(idx=0;idx<lat_nbr;idx++){ (void)fprintf(stdout,"lat[%li] = %g, vertices = ",idx,lat_ctr[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lat_bnd[bnd_nbr*idx+bnd_idx],bnd_idx == bnd_nbr-1 ? "]\n" : ", "); } /* end loop over lat */ for(idx=0;idx<lon_nbr;idx++){ (void)fprintf(stdout,"lon[%li] = %g, vertices = ",idx,lon_ctr[idx]); for(bnd_idx=0;bnd_idx<bnd_nbr;bnd_idx++) (void)fprintf(stdout,"%s%g%s",bnd_idx == 0 ? "[" : "",lon_bnd[bnd_nbr*idx+bnd_idx],bnd_idx == bnd_nbr-1 ? "]\n" : ", "); } /* end loop over lon */ } /* endif dbg */ /* Fuzzy test of latitude weight normalization */ //const double eps_rlt_max=1.0e-14; /* [frc] Round-off error tolerance: Used 1.0e-14 until 20180904 */ const double eps_rlt_max=1.0e-12; /* [frc] Round-off error tolerance: Used 1.0e-12 since 20180904 */ lat_wgt_ttl=0.0; for(idx=0;idx<lat_nbr;idx++) lat_wgt_ttl+=lat_wgt[idx]; if(grd_typ == nco_grd_2D_fv || grd_typ == nco_grd_2D_eqa){ double lat_wgt_ttl_xpc; /* [frc] Expected sum of latitude weights */ lat_wgt_ttl_xpc=fabs(sin(dgr2rdn*lat_bnd[2*(lat_nbr-1)+1L])-sin(dgr2rdn*lat_bnd[0L])); if(grd_typ != nco_grd_2D_unk && fabs(1.0-lat_wgt_ttl/lat_wgt_ttl_xpc) > eps_rlt_max){ (void)fprintf(stdout,"%s: ERROR %s reports grid normalization does not meet precision tolerance eps_rlt_max = %20.15f\nlat_wgt_ttl = %20.15f, lat_wgt_ttl_xpc = %20.15f, lat_wgt_frc = %20.15f, eps_rlt = %20.15f\n",nco_prg_nm_get(),fnc_nm,eps_rlt_max,lat_wgt_ttl,lat_wgt_ttl_xpc,lat_wgt_ttl/lat_wgt_ttl_xpc,1.0-lat_wgt_ttl/lat_wgt_ttl_xpc); nco_exit(EXIT_FAILURE); } /* !imprecise */ } /* !nco_grd_lat_eqa, !nco_grd_lat_fv */ } /* !flg_grd_2D */ if(flg_grd_2D){ assert(grd_crn_nbr == 4); if(flg_dgn_bnd || (lat_bnd_id == NC_MIN_INT && lon_bnd_id == NC_MIN_INT)){ /* If interfaces were diagnosed from centers, copy corners from interfaces */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx=grd_crn_nbr*lon_idx; lon_crn[idx]=lon_ntf[lon_idx]; /* LL */ lon_crn[idx+1L]=lon_ntf[lon_idx+1L]; /* LR */ lon_crn[idx+2L]=lon_ntf[lon_idx+1L]; /* UR */ lon_crn[idx+3L]=lon_ntf[lon_idx]; /* UL */ } /* !lon_idx */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ idx=grd_crn_nbr*lat_idx; lat_crn[idx]=lat_ntf[lat_idx]; /* LL */ lat_crn[idx+1L]=lat_ntf[lat_idx]; /* LR */ lat_crn[idx+2L]=lat_ntf[lat_idx+1L]; /* UR */ lat_crn[idx+3L]=lat_ntf[lat_idx+1L]; /* UL */ } /* !lat_idx */ }else{ /* !lat_bnd_id */ /* If boundaries were provided in input dataset, copy corners from boundaries */ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx=grd_crn_nbr*lon_idx; lon_crn[idx]=lon_bnd[2*lon_idx]; /* LL */ lon_crn[idx+1L]=lon_bnd[2*lon_idx+1L]; /* LR */ lon_crn[idx+2L]=lon_bnd[2*lon_idx+1L]; /* UR */ lon_crn[idx+3L]=lon_bnd[2*lon_idx]; /* UL */ } /* !lon_idx */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ idx=grd_crn_nbr*lat_idx; lat_crn[idx]=lat_bnd[2*lat_idx]; /* LL */ lat_crn[idx+1L]=lat_bnd[2*lat_idx]; /* LR */ lat_crn[idx+2L]=lat_bnd[2*lat_idx+1L]; /* UR */ lat_crn[idx+3L]=lat_bnd[2*lat_idx+1L]; /* UL */ } /* !lat_idx */ } /* !lat_bnd_id */ } /* !flg_grd_2D */ /* lat/lon_crn will not change anymore so stuff rectangular arrays into unrolled arrays */ if(flg_grd_1D){ for(idx=0;idx<grd_sz_nbr;idx++){ grd_ctr_lat[idx]=lat_ctr[idx]; grd_ctr_lon[idx]=lon_ctr[idx]; if(flg_wrt_crn){ for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; grd_crn_lat[idx2]=lat_crn[idx2]; grd_crn_lon[idx2]=lon_crn[idx2]; } /* !crn */ }else{ /* !flg_wrt_crn */ /* Defaults for ERWG when corners are unknown */ for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; grd_crn_lat[idx2]=0.0; grd_crn_lon[idx2]=0.0; } /* !crn */ } /* !flg_wrt_crn */ } /* !col */ } /* !flg_grd_1D */ if(flg_grd_2D){ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++){ for(lon_idx=0;lon_idx<lon_nbr;lon_idx++){ idx=lat_idx*lon_nbr+lon_idx; grd_ctr_lat[idx]=lat_ctr[lat_idx]; grd_ctr_lon[idx]=lon_ctr[lon_idx]; for(crn_idx=0;crn_idx<grd_crn_nbr;crn_idx++){ idx2=grd_crn_nbr*idx+crn_idx; lat_idx2=lat_idx*grd_crn_nbr+crn_idx; lon_idx2=lon_idx*grd_crn_nbr+crn_idx; grd_crn_lat[idx2]=lat_crn[lat_idx2]; grd_crn_lon[idx2]=lon_crn[lon_idx2]; } /* !crn */ } /* !lon */ } /* !lat */ /* 20190613: Convert CW quadrilaterals to CCW quadrilaterals so TempestRemap accepts grids Default construction/inferral method orders corners CCW and CW for s2n and n2s grids, respectively */ if(!flg_s2n){ for(idx=0L;idx<grd_sz_nbr;idx++){ idx2=grd_crn_nbr*idx; flg_ccw=nco_ccw_chk(grd_crn_lat+idx2,grd_crn_lon+idx2,grd_crn_nbr,idx_ccw,rcr_lvl); } /* !idx */ } /* !flg_s2n */ } /* !flg_grd_2D */ /* Find span of all grids */ double lat_max; /* [dgr] Maximum latitude */ double lat_min; /* [dgr] Minimum latitude */ double lon_max; /* [dgr] Maximum longitude */ double lon_min; /* [dgr] Minimum longitude */ idx_ctr=0; if(has_mss_val_ctr){ /* Find first non-missing value center and thus corners */ for(idx_ctr=0;idx_ctr<grd_sz_nbr;idx_ctr++){ if(grd_ctr_lat[idx_ctr] != mss_val_ctr_dbl) break; } /* !grd_sz_nbr */ assert(idx_ctr != grd_sz_nbr); } /* !has_mss_val_ctr */ if(flg_wrt_crn){ /* Grids with corner boundaries supplied or inferred */ lon_max=grd_crn_lon[idx_ctr*grd_crn_nbr]; lat_max=grd_crn_lat[idx_ctr*grd_crn_nbr]; lon_min=grd_crn_lon[idx_ctr*grd_crn_nbr]; lat_min=grd_crn_lat[idx_ctr*grd_crn_nbr]; for(idx=1;idx<grd_sz_nbr*grd_crn_nbr;idx++){ idx_ctr=idx/grd_crn_nbr; if(has_mss_val_ctr) if(grd_ctr_lat[idx_ctr] == mss_val_ctr_dbl) continue; lat_max=(grd_crn_lat[idx] > lat_max) ? grd_crn_lat[idx] : lat_max; lon_max=(grd_crn_lon[idx] > lon_max) ? grd_crn_lon[idx] : lon_max; lat_min=(grd_crn_lat[idx] < lat_min) ? grd_crn_lat[idx] : lat_min; lon_min=(grd_crn_lon[idx] < lon_min) ? grd_crn_lon[idx] : lon_min; } /* !idx */ }else{ /* !flg_wrt_crn */ /* 20170424: Diagnose grid-extent when corners were not provided or inferred This is usually (always?) for 1d unstructured grids with only centers provided */ lon_max=grd_ctr_lon[idx_ctr]; lat_max=grd_ctr_lat[idx_ctr]; lon_min=grd_ctr_lon[idx_ctr]; lat_min=grd_ctr_lat[idx_ctr]; for(idx_ctr=1;idx_ctr<grd_sz_nbr;idx_ctr++){ if(has_mss_val_ctr) if(grd_ctr_lat[idx_ctr] == mss_val_ctr_dbl) continue; lat_max=(grd_ctr_lat[idx_ctr] > lat_max) ? grd_ctr_lat[idx_ctr] : lat_max; lon_max=(grd_ctr_lon[idx_ctr] > lon_max) ? grd_ctr_lon[idx_ctr] : lon_max; lat_min=(grd_ctr_lat[idx_ctr] < lat_min) ? grd_ctr_lat[idx_ctr] : lat_min; lon_min=(grd_ctr_lon[idx_ctr] < lon_min) ? grd_ctr_lon[idx_ctr] : lon_min; } /* !idx_ctr */ } /* flg_wrt_crn */ lat_spn=lat_max-lat_min; lon_spn=lon_max-lon_min; /* Use strict rules for rectangular grids, looser for spans that are inferred, or center-to-center not corner-to-corner */ if(flg_grd_2D){ if((float)lon_spn == 360.0f && (float)lat_spn == 180.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; }else{ /* !flg_grd_2D */ if((float)lon_spn >= 340.0f && (float)lat_spn >= 170.0f) nco_grd_xtn=nco_grd_xtn_glb; else nco_grd_xtn=nco_grd_xtn_rgn; } /* flg_wrt_crn */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s reports grid resolution %li x %li, spans %g x %g %s: [%g <= lat <= %g], [%g <= lon <= %g]\n",nco_prg_nm_get(),fnc_nm,lat_nbr,lon_nbr,lat_spn,lon_spn,ngl_unt ? ngl_unt : "degrees (probably)",lat_min,lat_max,lon_min,lon_max); if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s diagnosed input grid-extent: %s\n",nco_prg_nm_get(),fnc_nm,nco_grd_xtn_sng(nco_grd_xtn)); /* Write ERWG hints if filenames provided and grid is regional */ char *fl_hnt=NULL; char *fl_hnt_dst=NULL; char *fl_hnt_src=NULL; if(rgr->fl_hnt_dst) fl_hnt=fl_hnt_dst=rgr->fl_hnt_dst; if(rgr->fl_hnt_src) fl_hnt=fl_hnt_src=rgr->fl_hnt_src; if(nco_grd_xtn == nco_grd_xtn_rgn && fl_hnt){ const char *fl_mode="w"; FILE *fp_hnt; /* [fl] Hint file (for ERWG switches) file handle */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s writing ERWG weight-generation regional hint to file %s\n",nco_prg_nm_get(),fnc_nm,fl_hnt); /* Open output file */ if((fp_hnt=fopen(fl_hnt,fl_mode)) == NULL){ (void)fprintf(stderr,"%s: ERROR unable to open hint output file %s\n",nco_prg_nm_get(),fl_hnt); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: Opened hint file %s\n",nco_prg_nm_get(),fl_hnt); if(fl_hnt_src) (void)fprintf(fp_hnt,"--src_regional"); if(fl_hnt_dst) (void)fprintf(fp_hnt,"--dst_regional"); rcd=fclose(fp_hnt); if(rcd != 0){ (void)fprintf(stderr,"%s: ERROR unable to close hint output file %s\n",nco_prg_nm_get(),fl_hnt); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: Closed hint file %s\n",nco_prg_nm_get(),fl_hnt); } /* !nco_grd_xtn */ /* Diagnose area if necessary 20170510: ALM/CLM "area" is _FillValue=1.0e36f over ocean and total gridcell area in km2 (not multiplied by landfrac) elsewhere Writing this ALM/CLM "area" variable to gridfile, then using with ERWG --user_areas could be disastrous (depending on mask array and interpolation type) On the other hand CAM "area" variable is exactly what we want for gridfile Input areas are considered "untrustworthy" iff they have _and use_ missing value attribute Re-diagnose areas considered untrustworthy so output area array does not contain missing values */ if(flg_wrt_crn && has_mss_val_area){ const double mss_val_dbl=mss_val_area_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(area[idx] == mss_val_dbl) break; if(idx < grd_sz_nbr) use_mss_val_area=True; if(nco_dbg_lvl_get() >= nco_dbg_fl && use_mss_val_area) (void)fprintf(stdout,"%s: INFO %s reports input area field %s is considered untrustworthy because it uses missing values, will diagnose area from cell boundaries instead...\n",nco_prg_nm_get(),fnc_nm,area_nm_in); } /* !has_mss_val_area */ /* 20170511: There remain a handful of cases when input area should be diagnosed not copied These include using ncremap in SGS mode when inferred grids must use sensible area units Otherwise an inferred grid with area [km2] from EAM/CLM might be combined with area [sr] from NCO This would bias ERWG --user_areas produced values by ~10^10 Setting flg_dgn_area ensures inferred area uses [sr] */ if(flg_wrt_crn && /* If bounds are available to compute area and ... */ (area_id == NC_MIN_INT || /* Area is not in input file ... */ use_mss_val_area || /* Area is untrustworthy */ flg_dgn_area)){ /* User/application explicitly requests diagnostic area */ /* Not absolutely necessary to diagnose area because ERWG will diagnose and output area itself _unless_ --user_areas option is given */ if(nco_dbg_lvl_get() >= nco_dbg_std && flg_dgn_area) (void)fprintf(stdout,"%s: INFO %s reports diagnosing area from cell boundaries...\n",nco_prg_nm_get(),fnc_nm); if(flg_grd_crv || flg_grd_1D){ /* Area of arbitrary unstructured or curvilinear grids requires spherical trigonometry */ nco_sph_plg_area(rgr,grd_crn_lat,grd_crn_lon,grd_sz_nbr,grd_crn_nbr,area); }else if(flg_grd_2D){ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr;lon_idx++) area[lat_idx*lon_nbr+lon_idx]=fabs(dgr2rdn*(lon_bnd[2*lon_idx+1L]-lon_bnd[2*lon_idx])*(sin(dgr2rdn*lat_bnd[2*lat_idx+1L])-sin(dgr2rdn*lat_bnd[2*lat_idx]))); /* fabs() ensures positive area in n2s grids */ } /* !flg_grd_2D */ flg_area_sr=True; } /* !area_id */ /* ERWG will fail unless grid file has mask variable Use nul-mask (all points included) whenever input mask variable not supplied/detected Define nul-mask true everywhere and overwrite with false below Input mask can be any type and output mask will always be NC_INT */ for(idx=0;idx<grd_sz_nbr;idx++) msk[idx]=1; if(msk_id != NC_MIN_INT){ /* Change missing-value-masked points to 0 integer mask for SCRIP grids (SCRIP has no missing value convention) Input mask can be any type and output mask will always be NC_INT Applications: ALM/CLM mask (landmask) is NC_FLOAT and defines though does not use NC_FLOAT missing value CICE mask (tmask/umask) is NC_FLOAT and defines and uses NC_FLOAT missing value RACMO mask is NC_FLOAT and defines though does not use NC_FLOAT missing value AMSR mask is NC_SHORT and has no missing value GHRSST mask is NC_BYTE and is a multi-valued surface-type flag with missing value == -1b */ if(msk_typ != NC_INT){ if(nco_dbg_lvl_get() == nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s mask variable \"%s\" has odd type = %s. Re-run with higher debugging level for more information.\n",nco_prg_nm_get(),fnc_nm,msk_nm_in,nco_typ_sng(msk_typ)); if(nco_dbg_lvl_get() > nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s mask variable \"%s\" has odd type = %s. Regridding weight generators require a mask variable of type NC_INT to specify points to include/exclude as sources/destinations. Points where the mask variable is zero or the missing value will be excluded (ignored) in regridding, all other points will be included. When inferring gridfiles, NCO assumes the first variable with a \"mask\"-like name (\"mask\", \"Mask\", \"grid_imask\", \"landmask\", or \"tmask\"), or the variable designated by the \"--msk_[src/dst]=msk_nm\" option, is this mask. However the variable \"%s\" in this file is not type NC_INT and so may not be intended as a regridding mask, hence this oh so pleasant informational WARNING. To prevent NCO from interpreting \"%s\" as a regridding mask, specify \"--msk_src=none\" and/or \"--msk_dst=none\", as appropriate. To utilize some other variable as the mask variable, specify \"--msk_src=msk_nm\" and/or \"--msk_dst=msk_nm\", as appropriate. Mask treatment is subtle, and NCO tries to \"do the right thing\". Whether it does is often easiest to discern by visual inspection of the regridded results in a turn-key viewer like Panoply or ncview.\n",nco_prg_nm_get(),fnc_nm,msk_nm_in,nco_typ_sng(msk_typ),msk_nm_in,msk_nm_in); } /* msk_typ */ switch(msk_typ){ case NC_FLOAT: if(has_mss_val_msk){ const float mss_val_flt=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.fp[idx] == mss_val_flt || msk_unn.fp[idx] == 0.0f) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.fp[idx] == 0.0f) msk[idx]=0; } /* !mss_val */ break; case NC_DOUBLE: if(has_mss_val_msk){ const double mss_val_dbl=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.dp[idx] == mss_val_dbl || msk_unn.dp[idx] == 0.0) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.dp[idx] == 0.0) msk[idx]=0; } /* !mss_val */ break; case NC_INT: if(has_mss_val_msk){ const int mss_val_int=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.ip[idx] == mss_val_int || msk_unn.ip[idx] == 0) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.ip[idx] == 0) msk[idx]=0; } /* !mss_val */ break; case NC_SHORT: /* http://stackoverflow.com/questions/208433/how-do-i-write-a-short-literal-in-c */ if(has_mss_val_msk){ const short mss_val_sht=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.sp[idx] == mss_val_sht || msk_unn.sp[idx] == ((short)0)) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.sp[idx] == ((short)0)) msk[idx]=0; /* 20160111: AMSR kludge fxm */ // for(idx=0;idx<grd_sz_nbr;idx++) if(msk[idx] == 1) msk[idx]=0; } /* !mss_val */ break; case NC_BYTE: if(has_mss_val_msk){ const nco_byte mss_val_byt=mss_val_msk_dbl; for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.bp[idx] == mss_val_byt || msk_unn.bp[idx] == ((nco_byte)0)) msk[idx]=0; }else{ for(idx=0;idx<grd_sz_nbr;idx++) if(msk_unn.bp[idx] == ((nco_byte)0)) msk[idx]=0; /* 20170811: GHRSST kludge? */ } /* !mss_val */ break; default: (void)fprintf(stderr,"%s: ERROR %s mask variable \"%s\" has unsupported type = %s\n",nco_prg_nm_get(),fnc_nm,msk_nm_in,nco_typ_sng(msk_typ)); nco_dfl_case_generic_err(); return NCO_ERR; break; } /* !msk_typ */ if(msk_unn.vp) msk_unn.vp=(void *)nco_free(msk_unn.vp); } /* !msk_id */ if(nco_dbg_lvl_get() >= nco_dbg_scl){ lat_wgt_ttl=0.0; area_ttl=0.0; if(flg_grd_2D){ (void)fprintf(stderr,"%s: INFO %s reports inferred rectangular latitude grid area diagnostics (lat_wgt_ttl and frc_lat_wgt should be valid):\n",nco_prg_nm_get(),fnc_nm); for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) lat_wgt_ttl+=lat_wgt[lat_idx]; }else{ (void)fprintf(stderr,"%s: INFO %s reports inferred unstructured or curvilinear latitude grid area diagnostics (ignore lat_wgt_ttl and frc_lat_wgt):\n",nco_prg_nm_get(),fnc_nm); } /* !flg_grd_2D */ for(lat_idx=0;lat_idx<lat_nbr;lat_idx++) for(lon_idx=0;lon_idx<lon_nbr;lon_idx++) area_ttl+=area[lat_idx*lon_nbr+lon_idx]; (void)fprintf(stdout,"lat_wgt_ttl = %20.15f, frc_lat_wgt = %20.15f, area_ttl = %20.15f, frc_area = %20.15f\n",lat_wgt_ttl,lat_wgt_ttl/2.0,area_ttl,area_ttl/(4.0*M_PI)); assert(area_ttl > 0.0); /* Protect following assertion since area might be in, e.g., km2 (ELM, RACMO) */ if(flg_area_sr) assert(area_ttl <= 4.0*M_PI); const double eps_rlt_area=1.0e-12; /* [frc] Error tolerance for global area */ if(nco_grd_xtn == nco_grd_xtn_glb){ if(fabs(1.0-area_ttl/(4.0*M_PI)) > eps_rlt_area) (void)fprintf(stdout,"%s: WARNING %s reports area for inferred global grid differs from true global area (4*pi sr) by greater than allowed fraction %g\n",nco_prg_nm_get(),fnc_nm,eps_rlt_area); } /* !nco_grd_xtn_glb */ } /* !dbg */ /* Open grid file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Define dimensions */ /* 20151230 ERWG appears to require presence of corner arrays in grid file even when they are not used (e.g., bilinear) But ERWG will break when corner values are bad. Default is do not write bad corner values. Uncomment next line to write bad corner values. */ /* flg_wrt_crn=True; */ if(flg_wrt_crn) rcd=nco_def_dim(out_id,grd_crn_nm,grd_crn_nbr,&dmn_id_grd_crn); rcd=nco_def_dim(out_id,grd_sz_nm,grd_sz_nbr,&dmn_id_grd_sz); rcd=nco_def_dim(out_id,grd_rnk_nm,grd_rnk_nbr,&dmn_id_grd_rnk); int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; /* Define variables */ (void)nco_def_var(out_id,dmn_sz_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_rnk,&dmn_sz_int_id); /* NB: Too small to deflate */ (void)nco_def_var(out_id,area_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&area_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,msk_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_grd_sz,&msk_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msk_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lat_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_ctr_lon_nm,crd_typ,dmn_nbr_1D,&dmn_id_grd_sz,&grd_ctr_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_ctr_lon_id,shuffle,deflate,dfl_lvl); if(flg_wrt_crn){ dmn_ids[0]=dmn_id_grd_sz; dmn_ids[1]=dmn_id_grd_crn; (void)nco_def_var(out_id,grd_crn_lat_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lat_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lat_id,shuffle,deflate,dfl_lvl); (void)nco_def_var(out_id,grd_crn_lon_nm,crd_typ,dmn_nbr_2D,dmn_ids,&grd_crn_lon_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,grd_crn_lon_id,shuffle,deflate,dfl_lvl); } /* !flg_wrt_crn */ /* Define attributes */ aed_sct aed_mtd; char *att_nm; if(strstr(rgr->grd_ttl,"None given")){ const char att_fmt[]="NCO inferred this grid from input file %s"; att_val=(char *)nco_malloc((strlen(att_fmt)+strlen(rgr->fl_in)+1L)*sizeof(char)); sprintf(att_val,att_fmt,rgr->fl_in); }else{ att_val=strdup(rgr->grd_ttl); } /* !grd_ttl */ rcd=nco_char_att_put(out_id,NULL,"title",att_val); rcd=nco_char_att_put(out_id,NULL,"Conventions","SCRIP"); const char usr_cpp[]=TKN2SNG(USER); /* [sng] Hostname from C pre-processor */ rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); rcd=nco_char_att_put(out_id,NULL,"grid_generator","NCO"); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,NULL,"latitude_grid_type",nco_grd_lat_sng(lat_typ)); rcd=nco_char_att_put(out_id,NULL,"longitude_grid_type",nco_grd_lon_sng(lon_typ)); rcd=nco_char_att_put(out_id,dmn_sz_nm,"long_name","Size(s) of horizontal dimensions (in Fortran storage order for historical reasons)"); if(flg_area_sr){ rcd=nco_char_att_put(out_id,area_nm,"long_name","Solid Angle Subtended on Grid"); rcd=nco_char_att_put(out_id,area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm,"units","steradian"); }else{ /* !flg_area_sr */ rcd=nco_char_att_put(out_id,area_nm,"long_name","Area on Grid"); // rcd=nco_char_att_put(out_id,area_nm,"standard_name","solid_angle"); rcd=nco_char_att_put(out_id,area_nm,"units",area_unt); } /* !flg_area_sr */ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"long_name","Latitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"standard_name","latitude"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"units","degrees"); } /* !ngl_unt */ rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"long_name","Longitude of Grid Cell Centers"); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"standard_name","longitude"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees_east"); else rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"units","degrees"); } /* !ngl_unt */ if(flg_wrt_crn){ rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"long_name","Latitude of Grid Cell Vertices"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_crn_lat_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_crn_lat_nm,"units","degrees"); } /* !ngl_unt */ rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"long_name","Longitude of Grid Cell Vertices"); if(ngl_unt){ rcd=nco_char_att_put(out_id,grd_crn_lon_nm,unt_sng,ngl_unt); }else{ /* 20191009: ERWG 7.1.0r- breaks on CF-compliant units strings */ if(rgr->flg_cf_units) rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees_north"); else rcd=nco_char_att_put(out_id,grd_crn_lon_nm,"units","degrees"); } /* !ngl_unt */ rcd=nco_char_att_put(out_id,grd_ctr_lat_nm,"bounds",grd_crn_lat_nm); rcd=nco_char_att_put(out_id,grd_ctr_lon_nm,"bounds",grd_crn_lon_nm); } /* !flg_wrt_crn */ rcd=nco_char_att_put(out_id,msk_nm,"long_name","Binary Integer Mask for Grid"); rcd=nco_char_att_put(out_id,msk_nm,"units","none"); /* Begin data mode */ (void)nco_enddef(out_id); /* Write variables */ dmn_srt[0]=0L; dmn_cnt[0]=grd_rnk_nbr; rcd=nco_put_vara(out_id,dmn_sz_int_id,dmn_srt,dmn_cnt,dmn_sz_int,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,area_id,dmn_srt,dmn_cnt,area,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,msk_id,dmn_srt,dmn_cnt,msk,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lat_id,dmn_srt,dmn_cnt,grd_ctr_lat,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=grd_sz_nbr; rcd=nco_put_vara(out_id,grd_ctr_lon_id,dmn_srt,dmn_cnt,grd_ctr_lon,crd_typ); if(flg_wrt_crn){ dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lat_id,dmn_srt,dmn_cnt,grd_crn_lat,crd_typ); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=grd_sz_nbr; dmn_cnt[1]=grd_crn_nbr; rcd=nco_put_vara(out_id,grd_crn_lon_id,dmn_srt,dmn_cnt,grd_crn_lon,crd_typ); } /* !flg_wrt_crn */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); fl_out=rgr->fl_ugrid; if(fl_out){ /* Test UGRID: Documentation: https://github.com/ugrid-conventions/ugrid-conventions Procedure: Create 1x1 skeleton file, infer UGRID and SCRIP grids from it ncks -O -D 1 --rgr ttl='Equiangular grid 180x360' --rgr skl=${HOME}/skl_180x360.nc --rgr scrip=${HOME}/grd_180x360_SCRIP.nc --rgr latlon=180,360#lat_typ=eqa#lon_typ=Grn_ctr ~/nco/data/in.nc ~/foo.nc ncks -O -D 1 --rgr infer --rgr ugrid=${HOME}/grd_ugrid.nc --rgr scrip=${HOME}/grd_scrip.nc ~/skl_180x360.nc ~/foo.nc ncks --cdl -v mesh_node_y ~/grd_ugrid.nc ncks --cdl -v mesh_face_nodes,mesh_face_x,mesh_face_y -d nFaces,0 ~/grd_ugrid.nc ncks --cdl -v mesh_edge_nodes,mesh_edge_x,mesh_edge_y -d nEdges,0 ~/grd_ugrid.nc ncks --cdl -v grid_center_lat,grid_corner_lat -d grid_size,0,,360 -d grid_corners,0,3 ~/grd_scrip.nc ncks --cdl -m -M ~/grd_ugrid.nc */ char *dgx_nm=NULL_CEWI; /* [sng] Name of edge_coordinates x variable */ char *dgy_nm=NULL_CEWI; /* [sng] Name of edge_coordinates y variable */ char *dg_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as edges */ char *dg_nd_nm=NULL_CEWI; /* [sng] Name of edge_node_connectivity variable */ char *fcx_nm=NULL_CEWI; /* [sng] Name of face_coordinates x variable */ char *fcy_nm=NULL_CEWI; /* [sng] Name of face_coordinates y variable */ char *fc_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as faces */ char *fc_nd_nm=NULL_CEWI; /* [sng] Name of face_node_connectivity variable */ char *msh_nm=NULL_CEWI; /* [sng] Name of mesh topology variable */ char *nd_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as nodes */ char *ndx_nm=NULL_CEWI; /* [sng] Name of node_coordinates x variable */ char *ndy_nm=NULL_CEWI; /* [sng] Name of node_coordinates y variable */ char *npe_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as nodes-per-edge */ char *npf_dmn_nm=NULL_CEWI; /* [sng] Name of dimension to recognize as nodes-per-face */ double *dgx=NULL_CEWI; /* [dgr] Characteristic longitude of edges */ double *dgy=NULL_CEWI; /* [dgr] Characteristic latitude of edges */ double *fcx=NULL_CEWI; /* [dgr] Characteristic longitude of faces */ double *fcy=NULL_CEWI; /* [dgr] Characteristic latitude of faces */ double *ndx=NULL_CEWI; /* [dgr] Longitude of nodes */ double *ndy=NULL_CEWI; /* [dgr] Latitude of nodes */ int *dg_nd; /* [idx] edge_node_connectivity variable */ int *fc_nd; /* [idx] face_node_connectivity variable */ int dg_nd_id=NC_MIN_INT; /* [id] edge_node_connectivity variable ID */ int dgx_id=NC_MIN_INT; /* [id] Characteristic longitude of edges variable ID */ int dgy_id=NC_MIN_INT; /* [id] Characteristic latitude of edges variable ID */ int dmn_id_dg=NC_MIN_INT; /* [id] Dimension ID for edges */ int dmn_id_fc=NC_MIN_INT; /* [id] Dimension ID for faces */ int dmn_id_nd=NC_MIN_INT; /* [id] Dimension ID for nodes */ int dmn_id_npe=NC_MIN_INT; /* [id] Dimension ID for nodes-per-edge */ int dmn_id_npf=NC_MIN_INT; /* [id] Dimension ID for nodes-per-face */ int fc_nd_id=NC_MIN_INT; /* [id] face_node_connectivity variable ID */ int fcx_id=NC_MIN_INT; /* [id] Characteristic longitude of faces variable ID */ int fcy_id=NC_MIN_INT; /* [id] Characteristic latitude of faces variable ID */ int msh_id=NC_MIN_INT; /* [id] Mesh topology variable ID */ int msh_val=42; /* [id] Mesh topology variable value from Monty Python */ int ndx_id=NC_MIN_INT; /* [id] Longitude of mesh nodes variable ID */ int ndy_id=NC_MIN_INT; /* [id] Latitude of mesh nodes variable ID */ const long fc_nbr=grd_sz_nbr; /* [nbr] Number of faces in mesh */ const long npe_nbr=2; /* [nbr] Number of nodes per edge */ const long npf_nbr=grd_crn_nbr; /* [nbr] Number of nodes per face */ long dg_idx; /* [idx] Counting index for edges */ long dg_nbr=(long)NC_MIN_INT64; /* [nbr] Number of edges in mesh */ long fc_idx; /* [idx] Counting index for faces */ long nd_idx; /* [idx] Counting index for nodes */ long nd_nbr=(long)NC_MIN_INT64; /* [nbr] Number of nodes in mesh */ long srt_idx=0; /* [idx] start_index (C/Fortran) for edge_nodes, face_nodes */ if(!dgx_nm) dgx_nm=(char *)strdup("mesh_edge_x"); if(!dgy_nm) dgy_nm=(char *)strdup("mesh_edge_y"); if(!dg_dmn_nm) dg_dmn_nm=(char *)strdup("nEdges"); if(!fcx_nm) fcx_nm=(char *)strdup("mesh_face_x"); if(!fcy_nm) fcy_nm=(char *)strdup("mesh_face_y"); if(!fc_dmn_nm) fc_dmn_nm=(char *)strdup("nFaces"); if(!dg_nd_nm) dg_nd_nm=(char *)strdup("mesh_edge_nodes"); if(!fc_nd_nm) fc_nd_nm=(char *)strdup("mesh_face_nodes"); if(!msh_nm) msh_nm=(char *)strdup("mesh"); if(!nd_dmn_nm) nd_dmn_nm=(char *)strdup("nNodes"); if(!ndx_nm) ndx_nm=(char *)strdup("mesh_node_x"); if(!ndy_nm) ndy_nm=(char *)strdup("mesh_node_y"); if(!npe_dmn_nm) npe_dmn_nm=(char *)strdup("two"); if(!npf_dmn_nm) npf_dmn_nm=(char *)strdup("maxNodesPerFace"); if(flg_grd_1D){ (void)fprintf(stdout,"%s: ERROR %s UGRID output does not yet support 1D grids\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); }else if(flg_grd_2D){ /* Assume 2D grids are global and comprised of quadrilaterals */ switch(lat_typ){ case nco_grd_lat_fv: /* Currently all 2D grids are converted to the same UGRID representation fxm: Cap grids (e.g., FV) should eventually be written with a real cap, rather than as the "polar teeth" representation currently used. Polar teeth convention allows cap grid to be represented as rectangular on disk However, cap grids are better suited to non-rectangular UGRID meshes */ case nco_grd_lat_eqa: case nco_grd_lat_gss: /* Numbers of unique edges and nodes counted from South Pole (SP) to North Pole (NP) */ dg_nbr=lon_nbr*2+ /* SP: cells_per_lat*unique_edges_per_cell */ (lat_nbr-2)*lon_nbr*2+ /* Mid: lats*cells_per_lat*unique_edges_per_cell */ lon_nbr*1; /* NP: cells_per_lat*unique_edges_per_cell */ nd_nbr=1+lon_nbr*1+ /* SP: SP+cells_per_lat*unique_nodes_per_cell */ (lat_nbr-2)*lon_nbr*1+ /* Mid: lats*cells_per_lat*unique_nodes_per_cell */ 1; /* NP: NP */ break; case nco_grd_lat_unk: case nco_grd_lat_nil: default: nco_dfl_case_generic_err(); break; } /* !lat_typ */ }else if(flg_grd_crv){ (void)fprintf(stdout,"%s: ERROR %s UGRID output does not yet support curvilinear grids\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !flg_grd */ dg_nd=(int *)nco_malloc(dg_nbr*npe_nbr*nco_typ_lng(NC_INT)); dgx=(double *)nco_malloc(dg_nbr*nco_typ_lng(crd_typ)); dgy=(double *)nco_malloc(dg_nbr*nco_typ_lng(crd_typ)); fc_nd=(int *)nco_malloc(fc_nbr*npf_nbr*nco_typ_lng(NC_INT)); fcx=(double *)nco_malloc(fc_nbr*nco_typ_lng(crd_typ)); fcy=(double *)nco_malloc(fc_nbr*nco_typ_lng(crd_typ)); ndx=(double *)nco_malloc(nd_nbr*nco_typ_lng(crd_typ)); ndy=(double *)nco_malloc(nd_nbr*nco_typ_lng(crd_typ)); const long int idx_fst_crn_ll=0; const long int idx_fst_crn_lr=1; const long int idx_fst_crn_ur=2; const long int idx_fst_crn_ul=3; /* Node Ordering: Each interior face requires one new node Node 0 at SP New latitude row moves next node North Add nodes to run West->East */ /* SP */ ndx[0]=lon_crn[0]; /* Longitude degenerate at SP, NP, keep same longitude as corner array */ ndy[0]=lat_crn[0]; /* Mid */ for(nd_idx=1;nd_idx<nd_nbr-1L;nd_idx++){ fc_idx=nd_idx-1L; lat_idx=fc_idx/lon_nbr; lon_idx=fc_idx%lon_nbr; ndx[nd_idx]=lon_crn[lon_idx*grd_crn_nbr+idx_fst_crn_ul]; ndy[nd_idx]=lat_crn[lat_idx*grd_crn_nbr+idx_fst_crn_ul]; } /* !nd_idx */ /* NP */ ndx[nd_nbr-1L]=lon_crn[(lon_nbr-1)*grd_crn_nbr+idx_fst_crn_ul]; ndy[nd_nbr-1L]=lat_crn[(lat_nbr-1)*grd_crn_nbr+idx_fst_crn_ul]; /* Edge Ordering: epf_nbr is number of distinct edges-per-face (incremental, for interior cells) Each additional interior rectangular gridcell requires two new edges: Edge 0 runs South->North for all cells Edge 1 runs West->East for all cells NP row requires only one new edge per face */ /* SP */ const int epf_nbr=2; /* [nbr] Number of distinct edges-per-face (incremental, for interior cells) */ for(fc_idx=0;fc_idx<lon_nbr;fc_idx++){ dg_idx=fc_idx*epf_nbr; /* Edge 0 */ dg_nd[(dg_idx+0L)*npe_nbr+0L]=srt_idx; dg_nd[(dg_idx+0L)*npe_nbr+1L]=srt_idx+fc_idx+1L; /* Edge 1 */ dg_nd[(dg_idx+1L)*npe_nbr+0L]=srt_idx+fc_idx+1L; dg_nd[(dg_idx+1L)*npe_nbr+1L]=srt_idx+fc_idx+2L; } /* !fc_idx */ /* Mid */ for(fc_idx=lon_nbr;fc_idx<(lat_nbr-1L)*lon_nbr;fc_idx++){ dg_idx=fc_idx*epf_nbr; /* Edge 0 */ dg_nd[(dg_idx+0L)*npe_nbr+0L]=srt_idx+fc_idx-lon_nbr+1L; dg_nd[(dg_idx+0L)*npe_nbr+1L]=srt_idx+fc_idx+1L; /* Edge 1 */ dg_nd[(dg_idx+1L)*npe_nbr+0L]=srt_idx+fc_idx+1L; dg_nd[(dg_idx+1L)*npe_nbr+1L]=srt_idx+fc_idx+2L; } /* !fc_idx */ /* NP */ for(fc_idx=fc_nbr-lon_nbr;fc_idx<fc_nbr;fc_idx++){ /* Only one new edge per face in last row, easiest to count backwards from last edge */ dg_idx=dg_nbr-(fc_nbr-fc_idx); /* NP faces require only only one new edge, Edge 0 */ dg_nd[(dg_idx+0L)*npe_nbr+0L]=srt_idx+fc_idx-lon_nbr+1L; dg_nd[(dg_idx+0L)*npe_nbr+1L]=srt_idx+nd_nbr-1L; } /* !fc_idx */ /* SP */ for(fc_idx=0;fc_idx<lon_nbr;fc_idx++){ fc_nd[fc_idx*npf_nbr+0L]=srt_idx+0L; fc_nd[fc_idx*npf_nbr+1L]=srt_idx+fc_idx+2L; /* NB: CCW */ fc_nd[fc_idx*npf_nbr+2L]=srt_idx+fc_idx+1L; /* NB: CCW */ fc_nd[fc_idx*npf_nbr+3L]=mss_val_int_out; } /* !fc_idx */ /* Mid */ for(fc_idx=lon_nbr;fc_idx<fc_nbr-lon_nbr;fc_idx++){ fc_nd[fc_idx*npf_nbr+idx_fst_crn_ll]=srt_idx+fc_idx-lon_nbr+1L; fc_nd[fc_idx*npf_nbr+idx_fst_crn_lr]=srt_idx+fc_idx-lon_nbr+2L; fc_nd[fc_idx*npf_nbr+idx_fst_crn_ur]=srt_idx+fc_idx+2L; fc_nd[fc_idx*npf_nbr+idx_fst_crn_ul]=srt_idx+fc_idx+1L; } /* !fc_idx */ /* NP */ for(fc_idx=fc_nbr-lon_nbr;fc_idx<fc_nbr;fc_idx++){ fc_nd[fc_idx*npf_nbr+0L]=srt_idx+nd_nbr-(fc_nbr-fc_idx)-2L; fc_nd[fc_idx*npf_nbr+1L]=srt_idx+nd_nbr-(fc_nbr-fc_idx)-1L; fc_nd[fc_idx*npf_nbr+2L]=srt_idx+nd_nbr-1L; fc_nd[fc_idx*npf_nbr+3L]=mss_val_int_out; } /* !fc_idx */ /* Characteristic coordinates */ for(dg_idx=0;dg_idx<dg_nbr-1L;dg_idx++){ idx=dg_idx*npe_nbr; dgx[dg_idx]=0.5*(ndx[dg_nd[idx+0L]]+ndx[dg_nd[idx+1L]]); dgy[dg_idx]=0.5*(ndy[dg_nd[idx+0L]]+ndy[dg_nd[idx+1L]]); } /* !dg_idx */ /* Degenerate longitude at SP, NP, causes weird characterisic longitude unless special care taken */ for(fc_idx=0;fc_idx<fc_nbr-1L;fc_idx++){ idx=fc_idx*npf_nbr; if(fc_idx < lon_nbr){ fcx[fc_idx]=0.5*(ndx[fc_nd[idx+1L]]+ndx[fc_nd[idx+2L]]); }else if(fc_idx >= fc_nbr-lon_nbr-1){ fcx[fc_idx]=0.5*(ndx[fc_nd[idx+0L]]+ndx[fc_nd[idx+1L]]); }else if(fc_nd[idx+3L] != mss_val_int_out){ /* fxm for fcx use nco_lon_crn_avg_brnch() and 3-node version too */ fcx[fc_idx]=0.25*(ndx[fc_nd[idx+0L]]+ndx[fc_nd[idx+1L]]+ndx[fc_nd[idx+2L]]+ndx[fc_nd[idx+3L]]); }else{ abort(); } /* !fc_idx */ if(fc_nd[idx+3L] != mss_val_int_out) fcy[fc_idx]=0.25*(ndy[fc_nd[idx+0L]]+ndy[fc_nd[idx+1L]]+ndy[fc_nd[idx+2L]]+ndy[fc_nd[idx+3L]]); else fcy[fc_idx]=0.33*(ndy[fc_nd[idx+0L]]+ndy[fc_nd[idx+1L]]+ndy[fc_nd[idx+2L]]); } /* !fc_idx */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); rcd=nco_def_dim(out_id,dg_dmn_nm,dg_nbr,&dmn_id_dg); rcd=nco_def_dim(out_id,fc_dmn_nm,fc_nbr,&dmn_id_fc); rcd=nco_def_dim(out_id,nd_dmn_nm,nd_nbr,&dmn_id_nd); rcd=nco_def_dim(out_id,npe_dmn_nm,npe_nbr,&dmn_id_npe); rcd=nco_def_dim(out_id,npf_dmn_nm,npf_nbr,&dmn_id_npf); dmn_ids[0]=dmn_id_dg; dmn_ids[1]=dmn_id_npe; rcd=nco_def_var(out_id,dg_nd_nm,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids,&dg_nd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,dg_nd_id,shuffle,deflate,dfl_lvl); dmn_ids[0]=dmn_id_fc; dmn_ids[1]=dmn_id_npf; rcd=nco_def_var(out_id,fc_nd_nm,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids,&fc_nd_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,fc_nd_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,msh_nm,(nc_type)NC_INT,dmn_nbr_0D,(int *)NULL,&msh_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,msh_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,ndx_nm,crd_typ,dmn_nbr_1D,&dmn_id_nd,&ndx_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ndx_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,ndy_nm,crd_typ,dmn_nbr_1D,&dmn_id_nd,&ndy_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,ndy_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,dgx_nm,crd_typ,dmn_nbr_1D,&dmn_id_dg,&dgx_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,dgx_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,dgy_nm,crd_typ,dmn_nbr_1D,&dmn_id_dg,&dgy_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,dgy_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,fcx_nm,crd_typ,dmn_nbr_1D,&dmn_id_fc,&fcx_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,fcx_id,shuffle,deflate,dfl_lvl); rcd=nco_def_var(out_id,fcy_nm,crd_typ,dmn_nbr_1D,&dmn_id_fc,&fcy_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,fcy_id,shuffle,deflate,dfl_lvl); if(strstr(rgr->grd_ttl,"None given")){ const char att_fmt[]="NCO constructed this UGRID grid from scratch"; att_val=(char *)nco_malloc((strlen(att_fmt)+strlen(rgr->fl_in)+1L)*sizeof(char)); sprintf(att_val,att_fmt); }else{ att_val=strdup(rgr->grd_ttl); } /* !grd_ttl */ rcd=nco_char_att_put(out_id,NULL,"title",att_val); rcd=nco_char_att_put(out_id,NULL,"Conventions","CF-1.6, UGRID-1.0"); rcd=nco_char_att_put(out_id,NULL,"created_by",usr_cpp); rcd=nco_char_att_put(out_id,NULL,"grid_generator","NCO"); (void)nco_hst_att_cat(out_id,rgr->cmd_ln); (void)nco_vrs_att_cat(out_id); rcd=nco_char_att_put(out_id,msh_nm,"cf_role","mesh_topology"); rcd=nco_char_att_put(out_id,msh_nm,"standard_name","mesh_topology"); rcd=nco_char_att_put(out_id,msh_nm,"long_name","Topology data"); att_nm=strdup("topology_dimension"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=msh_nm; aed_mtd.id=msh_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&val_two; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,msh_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); aed_mtd.sz=strlen(ndx_nm)+strlen(ndy_nm)+1L; att_val=(char *)nco_malloc((aed_mtd.sz+1L)*nco_typ_lng(NC_CHAR)); (void)sprintf(att_val,"%s %s",ndx_nm,ndy_nm); rcd=nco_char_att_put(out_id,msh_nm,"node_coordinates",att_val); rcd=nco_char_att_put(out_id,msh_nm,"face_node_connectivity",fc_nd_nm); aed_mtd.sz=strlen(fcx_nm)+strlen(fcy_nm)+1L; att_val=(char *)nco_malloc((aed_mtd.sz+1L)*nco_typ_lng(NC_CHAR)); (void)sprintf(att_val,"%s %s",fcx_nm,fcy_nm); rcd=nco_char_att_put(out_id,msh_nm,"face_coordinates",att_val); rcd=nco_char_att_put(out_id,msh_nm,"face_dimension",fc_dmn_nm); rcd=nco_char_att_put(out_id,msh_nm,"edge_node_connectivity",dg_nd_nm); aed_mtd.sz=strlen(dgx_nm)+strlen(dgy_nm)+1L; att_val=(char *)nco_malloc((aed_mtd.sz+1L)*nco_typ_lng(NC_CHAR)); (void)sprintf(att_val,"%s %s",dgx_nm,dgy_nm); rcd=nco_char_att_put(out_id,msh_nm,"edge_coordinates",att_val); rcd=nco_char_att_put(out_id,msh_nm,"edge_dimension",dg_dmn_nm); rcd=nco_char_att_put(out_id,ndx_nm,"standard_name","longitude"); rcd=nco_char_att_put(out_id,ndx_nm,"long_name","Longitude of mesh nodes"); rcd=nco_char_att_put(out_id,ndx_nm,"units","degrees_east"); rcd=nco_char_att_put(out_id,ndy_nm,"standard_name","latitude"); rcd=nco_char_att_put(out_id,ndy_nm,"long_name","Latitude of mesh nodes"); rcd=nco_char_att_put(out_id,ndy_nm,"units","degrees_north"); rcd=nco_char_att_put(out_id,dg_nd_nm,"cf_role","edge_node_connectivity"); rcd=nco_char_att_put(out_id,dg_nd_nm,"long_name","Maps every edge to the two nodes that it connects"); att_nm=strdup("start_index"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=dg_nd_nm; aed_mtd.id=dg_nd_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&val_zero; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,dg_nd_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,fc_nd_nm,"cf_role","face_node_connectivity"); rcd=nco_char_att_put(out_id,fc_nd_nm,"long_name","Maps every face to its corner nodes"); att_nm=strdup("start_index"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=fc_nd_nm; aed_mtd.id=fc_nd_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&val_zero; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,fc_nd_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); att_nm=strdup("_FillValue"); aed_mtd.att_nm=att_nm; aed_mtd.var_nm=fc_nd_nm; aed_mtd.id=fc_nd_id; aed_mtd.sz=1; aed_mtd.type=NC_INT; aed_mtd.val.ip=&mss_val_int_out; aed_mtd.mode=aed_create; (void)nco_aed_prc(out_id,fc_nd_id,aed_mtd); if(att_nm) att_nm=(char *)nco_free(att_nm); rcd=nco_char_att_put(out_id,dgx_nm,"standard_name","longitude"); rcd=nco_char_att_put(out_id,dgx_nm,"long_name","Characteristic longitude of 2D mesh face"); rcd=nco_char_att_put(out_id,dgx_nm,"units","degrees_east"); rcd=nco_char_att_put(out_id,dgy_nm,"standard_name","latitude"); rcd=nco_char_att_put(out_id,dgy_nm,"long_name","Characteristic latitude of 2D mesh face"); rcd=nco_char_att_put(out_id,dgy_nm,"units","degrees_north"); rcd=nco_char_att_put(out_id,fcx_nm,"standard_name","longitude"); rcd=nco_char_att_put(out_id,fcx_nm,"long_name","Characteristic longitude of 2D mesh edge"); rcd=nco_char_att_put(out_id,fcx_nm,"units","degrees_east"); rcd=nco_char_att_put(out_id,fcy_nm,"standard_name","latitude"); rcd=nco_char_att_put(out_id,fcy_nm,"long_name","Characteristic latitude of 2D mesh edge"); rcd=nco_char_att_put(out_id,fcy_nm,"units","degrees_north"); /* Begin data mode */ (void)nco_enddef(out_id); (void)nco_put_vara(out_id,msh_id,dmn_srt,dmn_cnt,&msh_val,(nc_type)NC_INT); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=dg_nbr; dmn_cnt[1]=epf_nbr; (void)nco_put_vara(out_id,dg_nd_id,dmn_srt,dmn_cnt,dg_nd,(nc_type)NC_INT); dmn_srt[0]=dmn_srt[1]=0L; dmn_cnt[0]=fc_nbr; dmn_cnt[1]=npf_nbr; (void)nco_put_vara(out_id,fc_nd_id,dmn_srt,dmn_cnt,fc_nd,(nc_type)NC_INT); dmn_srt[0]=0L; dmn_cnt[0]=nd_nbr; (void)nco_put_vara(out_id,ndx_id,dmn_srt,dmn_cnt,ndx,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=nd_nbr; (void)nco_put_vara(out_id,ndy_id,dmn_srt,dmn_cnt,ndy,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=dg_nbr; (void)nco_put_vara(out_id,dgx_id,dmn_srt,dmn_cnt,dgx,crd_typ); (void)nco_put_vara(out_id,dgy_id,dmn_srt,dmn_cnt,dgy,crd_typ); dmn_srt[0]=0L; dmn_cnt[0]=fc_nbr; (void)nco_put_vara(out_id,fcx_id,dmn_srt,dmn_cnt,fcx,crd_typ); (void)nco_put_vara(out_id,fcy_id,dmn_srt,dmn_cnt,fcy,crd_typ); /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); /* Free memory associated with output file */ if(dgx) dgx=(double *)nco_free(dgx); if(dgy) dgy=(double *)nco_free(dgy); if(dg_nd) dg_nd=(int *)nco_free(dg_nd); if(fcx) fcx=(double *)nco_free(fcx); if(fcy) fcy=(double *)nco_free(fcy); if(fc_nd) fc_nd=(int *)nco_free(fc_nd); if(ndx) ndx=(double *)nco_free(ndx); if(ndy) ndy=(double *)nco_free(ndy); /* Free strings */ if(dgx_nm) dgx_nm=(char *)nco_free(dgx_nm); if(dgy_nm) dgy_nm=(char *)nco_free(dgy_nm); if(dg_dmn_nm) dg_dmn_nm=(char *)nco_free(dg_dmn_nm); if(dg_nd_nm) dg_nd_nm=(char *)nco_free(dg_nd_nm); if(fcx_nm) fcx_nm=(char *)nco_free(fcx_nm); if(fcy_nm) fcy_nm=(char *)nco_free(fcy_nm); if(fc_dmn_nm) fc_dmn_nm=(char *)nco_free(fc_dmn_nm); if(fc_nd_nm) fc_nd_nm=(char *)nco_free(fc_nd_nm); if(msh_nm) msh_nm=(char *)nco_free(msh_nm); if(nd_dmn_nm) nd_dmn_nm=(char *)nco_free(nd_dmn_nm); if(ndx_nm) ndx_nm=(char *)nco_free(ndx_nm); if(ndy_nm) ndy_nm=(char *)nco_free(ndy_nm); if(npe_dmn_nm) npe_dmn_nm=(char *)nco_free(npe_dmn_nm); if(npf_dmn_nm) npf_dmn_nm=(char *)nco_free(npf_dmn_nm); } /* !fl_ugrid */ /* Free memory associated with input file */ if(dmn_sz_int) dmn_sz_int=(int *)nco_free(dmn_sz_int); if(msk) msk=(int *)nco_free(msk); if(area) area=(double *)nco_free(area); if(grd_ctr_lat) grd_ctr_lat=(double *)nco_free(grd_ctr_lat); if(grd_ctr_lon) grd_ctr_lon=(double *)nco_free(grd_ctr_lon); if(grd_crn_lat) grd_crn_lat=(double *)nco_free(grd_crn_lat); if(grd_crn_lon) grd_crn_lon=(double *)nco_free(grd_crn_lon); if(lat_bnd) lat_bnd=(double *)nco_free(lat_bnd); if(lat_crn) lat_crn=(double *)nco_free(lat_crn); if(lat_ctr) lat_ctr=(double *)nco_free(lat_ctr); if(lat_ntf) lat_ntf=(double *)nco_free(lat_ntf); if(lat_wgt) lat_wgt=(double *)nco_free(lat_wgt); if(lon_bnd) lon_bnd=(double *)nco_free(lon_bnd); if(lon_crn) lon_crn=(double *)nco_free(lon_crn); if(lon_ctr) lon_ctr=(double *)nco_free(lon_ctr); if(lon_ntf) lon_ntf=(double *)nco_free(lon_ntf); if(edg_nbr_cll) edg_nbr_cll=(int *)nco_free(edg_nbr_cll); if(vrt_cll) vrt_cll=(int *)nco_free(vrt_cll); if(vrt_lat) vrt_lat=(double *)nco_free(vrt_lat); if(vrt_lon) vrt_lon=(double *)nco_free(vrt_lon); /* Free strings */ if(area_nm_in) area_nm_in=(char *)nco_free(area_nm_in); if(area_unt) area_unt=(char *)nco_free(area_unt); if(bnd_dmn_nm) bnd_dmn_nm=(char *)nco_free(bnd_dmn_nm); if(col_dmn_nm) col_dmn_nm=(char *)nco_free(col_dmn_nm); if(lat_bnd_nm) lat_bnd_nm=(char *)nco_free(lat_bnd_nm); if(lat_dmn_nm) lat_dmn_nm=(char *)nco_free(lat_dmn_nm); if(lat_nm_in) lat_nm_in=(char *)nco_free(lat_nm_in); if(lon_bnd_nm) lon_bnd_nm=(char *)nco_free(lon_bnd_nm); if(lon_dmn_nm) lon_dmn_nm=(char *)nco_free(lon_dmn_nm); if(lon_nm_in) lon_nm_in=(char *)nco_free(lon_nm_in); if(msk_nm_in) msk_nm_in=(char *)nco_free(msk_nm_in); if(ngl_unt) ngl_unt=(char *)nco_free(ngl_unt); if(edg_nbr_cll_nm) edg_nbr_cll_nm=(char *)nco_free(edg_nbr_cll_nm); if(vrt_cll_nm) vrt_cll_nm=(char *)nco_free(vrt_cll_nm); if(vrt_lat_nm) vrt_lat_nm=(char *)nco_free(vrt_lat_nm); if(vrt_lon_nm) vrt_lon_nm=(char *)nco_free(vrt_lon_nm); return rcd; } /* !nco_grd_nfr() */ double /* O [dgr] Longitude difference (lon_r-lon_l) */ nco_lon_dff_brnch_dgr /* [fnc] Subtract longitudes with branch-cut rules */ (double lon_r, /* I [dgr] Longitude on right of gridcell (subtractor) */ double lon_l) /* I [dgr] Longitude on left of gridcell (subtractee) */ { /* Purpose: Return difference of two longitudes in degrees Assume longitudes are within 180 degrees of eachother Default orientation is monotonically increasing longitude from left to right */ const char fnc_nm[]="nco_lon_dff_brnch_dgr()"; const double lon_dff=lon_r-lon_l; /* [dgr] Longitude difference (lon_r-lon_l) */ if(lon_dff >= 180.0){ (void)fprintf(stdout,"%s: WARNING %s reports lon_r, lon_l, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_r,lon_l,lon_dff); return lon_dff-360.0; }else if(lon_dff <= -180.0){ return lon_dff+360.0; } /* !lon_dff */ return lon_dff; } /* !nco_lon_dff_brnch_dgr() */ double /* O [rdn] Longitude difference (lon_r-lon_l) */ nco_lon_dff_brnch_rdn /* [fnc] Subtract longitudes with branch-cut rules */ (double lon_r, /* I [rdn] Longitude on right of gridcell (subtractor) */ double lon_l) /* I [rdn] Longitude on left of gridcell (subtractee) */ { /* Purpose: Return difference of two longitudes in radians Assume longitudes are within pi radians of eachother Default orientation is monotonically increasing longitude from left to right */ const char fnc_nm[]="nco_lon_dff_brnch_rdn()"; const double lon_dff=lon_r-lon_l; /* [rdn] Longitude difference (lon_r-lon_l) */ //nco_bool dbg_prn=False; /* [flg] Print warning when longitude difference is suspicious */ /* longitudes on different branch cuts are expected when computing polygon area, so warn only if requested with high debugging level */ if(lon_dff >= M_PI){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports lon_r, lon_l, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_r,lon_l,lon_dff); return lon_dff-M_PI-M_PI; }else if(lon_dff <= -M_PI){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports lon_r, lon_l, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_r,lon_l,lon_dff); return lon_dff+M_PI+M_PI; } /* !lon_dff */ return lon_dff; } /* !nco_lon_dff_brnch_rdn() */ double /* O [dgr] Longitude average */ nco_lon_crn_avg_brnch /* [fnc] Average quadrilateral longitude with branch-cut rules */ (double lon_ll, /* I [dgr] Longitude at lower left of gridcell */ double lon_lr, /* I [dgr] Longitude at lower right of gridcell */ double lon_ur, /* I [dgr] Longitude at upper right of gridcell */ double lon_ul) /* I [dgr] Longitude at upper left of gridcell */ { /* Purpose: Return average of four corner longitudes of quadrilateral Assume longitudes are within 180 degrees of eachother Default orientation is monotonically increasing longitude from left to right WLOG, adjust all longitudes to be on same branch as lon_ll */ const char fnc_nm[]="nco_lon_crn_avg_brnch()"; double lon_dff; /* [dgr] Longitude difference */ lon_dff=lon_lr-lon_ll; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports lon_lr, lon_ll, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_lr,lon_ll,lon_dff); lon_lr-=360.0; }else if(lon_dff <= -180.0){ lon_lr+=360.0; } /* !lon_dff */ lon_dff=lon_ur-lon_ll; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports lon_ur, lon_ll, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_ur,lon_ll,lon_dff); lon_ur-=360.0; }else if(lon_dff <= -180.0){ lon_ur+=360.0; } /* !lon_dff */ lon_dff=lon_ul-lon_ll; if(lon_dff >= 180.0){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: INFO %s reports lon_ul, lon_ll, lon_dff = %g, %g, %g\n",nco_prg_nm_get(),fnc_nm,lon_ul,lon_ll,lon_dff); lon_ul-=360.0; }else if(lon_dff <= -180.0){ lon_ul+=360.0; } /* !lon_dff */ return 0.25*(lon_ll+lon_lr+lon_ur+lon_ul); } /* !nco_lon_crn_avg_brnch() */ double /* O [dgr] Longitude average */ nco_lon_ply_avg_brnch_dgr /* [fnc] Average polygon longitude with branch-cut rules */ (double *lon_crn, /* I [dgr] Longitude of gridcell corners */ long lon_nbr) /* I [nbr] Number of vertices in polygon */ { /* Purpose: Return average longitude of polygon vertices, i.e., centroid longitude Assume longitudes are within 180 degrees of one another Default orientation is monotonically increasing longitude from left to right WLOG, adjust all longitudes to be on same branch as lon_ll */ // const char fnc_nm[]="nco_lon_ply_avg_brnch()"; double lon_dff; /* [dgr] Longitude difference */ double lon_avg; /* [dgr] Longitude average */ int lon_idx; /* [idx] Polygon vertex index */ assert(lon_nbr != 0); lon_avg=lon_crn[0]; for(lon_idx=1;lon_idx<lon_nbr;lon_idx++){ lon_avg+=lon_crn[lon_idx]; lon_dff=lon_crn[lon_idx]-lon_crn[0]; if(lon_dff >= 180.0){ lon_avg-=360.0; }else if(lon_dff <= -180.0){ lon_avg+=360.0; } /* !lon_dff */ } /* !lon_idx */ return lon_avg/lon_nbr; } /* !nco_lon_ply_avg_brnch() */ nco_bool /* O [flg] Input corners were CCW */ nco_ccw_chk /* [fnc] Convert quadrilateral gridcell corners to CCW orientation */ (double * const crn_lat, /* [dgr] Latitude corners of gridcell */ double * const crn_lon, /* [dgr] Latitude corners of gridcell */ const int crn_nbr, /* [nbr] Number of corners per gridcell */ int idx_ccw, /* [idx] Index of starting vertice for CCW check (Point A = tail side AB) */ const int rcr_lvl) /* [nbr] Recursion level */ { /* Purpose: Determine whether corner vertices are oriented CCW If not, alter order so they are returned in CCW order Function can call itself, and rcr_lvl indicates recursion level: rcr_lvl=1: Called by host code, i.e., nco_grd_nfr() rcr_lvl=2: Called by itself, i.e., nco_ccw_chk() Assumptions: Quadrilateral vertices are already corrected to obey branch-cut rules, i.e., all vertices are on "same side" of dateline or Greenwich as appropriate Algorithm: Start crn_idx=0, i.e., quadrilateral LL corner Vector A runs from crn_idx=0 to crn_idx=1, i.e., quadrilateral LL->LR Vector B runs from crn_idx=1 to crn_idx=2, i.e., quadrilateral LR->UR Compute cross-product C = A x B C is normal to plane containing A and B Dot-product of C with radial vector to head A = tail B is positive if A and B are CCW if(ABC is CCW){ if(CDA is CCW) Done else Copy D:=A (make CDA degenerate, triangularize quadrilateral) endif }else(ABC is not CCW){ Assume entire quadrilateral is CW Take mirror image of quadrilateral by switching B with D If(new ABC is CCW){ If(CDA is CCW) Done else Copy D:=A (make CDA degenerate, triangularize quadrilateral) endif }else{ Fail (return False, meaning point should be masked) } All cases return True (i.e., CCW) from rcr_lvl=1 except last Last case returns False, and calling code should mask such an aberrant point */ const char fnc_nm[]="nco_ccw_chk()"; /* MSVC compiler chokes unless array size is compile-time constant */ const int CRN_NBR_MSVC=4; double sin_lat[CRN_NBR_MSVC]; double sin_lon[CRN_NBR_MSVC]; double cos_lat[CRN_NBR_MSVC]; double cos_lon[CRN_NBR_MSVC]; double A_tail_x,A_tail_y,A_tail_z; double A_head_x,A_head_y,A_head_z; double A_x,A_y,A_z; double B_tail_x,B_tail_y,B_tail_z; double B_head_x,B_head_y,B_head_z; double B_x,B_y,B_z; double C_x,C_y,C_z; double R_x,R_y,R_z; double lat_rdn; double lon_rdn; double dot_prd; int crn_idx; /* [idx] Corner idx */ int A_tail_idx,A_head_idx; int B_tail_idx,B_head_idx; nco_bool flg_ccw; /* [flg] Input is CCW */ assert(crn_nbr == CRN_NBR_MSVC); for(crn_idx=0;crn_idx<crn_nbr;crn_idx++){ lat_rdn=crn_lat[crn_idx]*M_PI/180.0; lon_rdn=crn_lon[crn_idx]*M_PI/180.0; sin_lat[crn_idx]=sin(lat_rdn); cos_lat[crn_idx]=cos(lat_rdn); sin_lon[crn_idx]=sin(lon_rdn); cos_lon[crn_idx]=cos(lon_rdn); } /* !crn_idx */ /* Calls from host code (i.e., nco_grd_nfr()) start at lower-left of quadrilateral ABCD = Point A = vertex 0 Calls from self can start from quadrilateral Point A or C To check triangle CDA, start at upper-right of quadrilateral ABCD = Point C = vertex 2 */ A_tail_idx=idx_ccw; A_head_idx=B_tail_idx=(A_tail_idx+1)%crn_nbr; B_head_idx=(B_tail_idx+1)%crn_nbr; A_tail_x=cos_lat[A_tail_idx]*cos_lon[A_tail_idx]; A_tail_y=cos_lat[A_tail_idx]*sin_lon[A_tail_idx]; A_tail_z=sin_lat[A_tail_idx]; A_head_x=B_tail_x=R_x=cos_lat[A_head_idx]*cos_lon[A_head_idx]; A_head_y=B_tail_y=R_y=cos_lat[A_head_idx]*sin_lon[A_head_idx]; A_head_z=B_tail_z=R_z=sin_lat[A_head_idx]; B_head_x=cos_lat[B_head_idx]*cos_lon[B_head_idx]; B_head_y=cos_lat[B_head_idx]*sin_lon[B_head_idx]; B_head_z=sin_lat[B_head_idx]; A_x=A_head_x-A_tail_x; A_y=A_head_y-A_tail_y; A_z=A_head_z-A_tail_z; B_x=B_head_x-B_tail_x; B_y=B_head_y-B_tail_y; B_z=B_head_z-B_tail_z; /* Cross-Product C = A x B */ C_x=A_y*B_z-B_y*A_z; C_y=-A_x*B_z+B_x*A_z; C_z=A_x*B_y-B_x*A_y; /* Dot-Product R dot C */ dot_prd=C_x*R_x+C_y*R_y+C_z*R_z; if(dot_prd > 0.0) flg_ccw=True; else flg_ccw=False; if(flg_ccw && crn_nbr == 4 && rcr_lvl == 1){ /* Original ABC is CCW, now check CDA */ idx_ccw=2; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,crn_nbr,idx_ccw,rcr_lvl+1); if(!flg_ccw){ if(nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports triangle ABC is and CDA is not CCW in quadrilateral gridcell with LL (lat,lon) = (%g, %g), dot_prd = %g. Setting D:=A to triangularize quadrilateral.\n",nco_prg_nm_get(),fnc_nm,*crn_lat+0,*crn_lon+0,dot_prd); /* Triangularize quadrilateral D:=A */ /* 20210411: From 2016 until today, nco_ccw_chk() overwrote fourth (UL) with first (LL) corner right here even when flg_ccw was True :( */ crn_lat[3]=crn_lat[0]; crn_lon[3]=crn_lon[0]; return True; } /* !flg_ccw */ }else if(!flg_ccw && crn_nbr == 4 && rcr_lvl == 1){ /* Original ABC is not CCW 20160124: Simplistic fix: reverse gridpoint order This only works for quadrilaterals without degenerate points */ double crn_tmp; if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: INFO %s reports triangle ABC is non-CCW in quadrilateral gridcell with LL (lat,lon) = (%g, %g), dot_prd = %g. Mirror-imaging...\n",nco_prg_nm_get(),fnc_nm,*crn_lat+0,*crn_lon+0,dot_prd); crn_tmp=crn_lat[1]; crn_lat[1]=crn_lat[3]; crn_lat[3]=crn_tmp; crn_tmp=crn_lon[1]; crn_lon[1]=crn_lon[3]; crn_lon[3]=crn_tmp; /* Check new triangle ABC */ idx_ccw=0; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,crn_nbr,idx_ccw,rcr_lvl+1); if(flg_ccw){ /* Inverted ABC is CCW, now check CDA */ idx_ccw=2; flg_ccw=nco_ccw_chk(crn_lat,crn_lon,crn_nbr,idx_ccw,rcr_lvl+1); if(flg_ccw){ return True; }else{ if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_io) (void)fprintf(stdout,"%s: INFO %s reports triangle ABC is CCW after inversion, but triangle CDA is not at quadrilateral gridcell with LL (lat,lon) = (%g, %g), dot_prd = %g. Setting D:=A to triangularize quadrilateral.\n",nco_prg_nm_get(),fnc_nm,*crn_lat+0,*crn_lon+0,dot_prd); /* Triangularize quadrilateral D:=A */ crn_lat[3]=crn_lat[0]; crn_lon[3]=crn_lon[0]; return True; } /* flg_ccw */ }else{ /* Original and Inverted ABC are not CCW */ if(!flg_ccw && nco_dbg_lvl_get() >= nco_dbg_crr) (void)fprintf(stdout,"%s: WARNING %s reports triangle ABC remains non-CCW after first inversion\n",nco_prg_nm_get(),fnc_nm); return False; } /* !flg_ccw */ } /* flg_ccw */ return flg_ccw; } /* !nco_ccw_chk() */
openssl_enc_fmt_plug.c
/* OpenSSL "enc" cracker for JtR. * * This software is Copyright (c) 2013, Dhiru Kholia <dhiru at openwall.com> * * $ openssl enc -aes-256-cbc -p -e -a -salt -in hello.txt -out hello.txt.enc * enter aes-256-cbc encryption password: * Verifying - enter aes-256-cbc encryption password: * salt=305CEDC2A0521011 * key=E08A1E6E1493BD3D3DAA25E112259D1688F7A0302AC8C16208DBDCEF179765F0 * iv =582FDDF9603B9B03A54FC0BB34370DDE * * $ cat hello.txt * 123456789012 * * Input Format: * * $openssl$cipher$md$salt-size$salt$last-chunks$inlined$known-plaintext$plaintext * $openssl$cipher$md$salt-size$salt$last-chunks$0$datalen$data$known-plaintext$plaintext */ #if FMT_EXTERNS_H extern struct fmt_main fmt_openssl; #elif FMT_REGISTERS_H john_register_one(&fmt_openssl); #else #if AC_BUILT #include "autoconfig.h" #endif #ifdef __CYGWIN__ // cygwin has HORRIBLE performance GOMP for this format it runs at 1/#cpu's the speed of OMP_NUM_THREADS=1 or non-GMP build #undef _OPENMP #undef FMT_OMP #undef FMT_OMP_BAD #define FMT_OMP 0 #define FMT_OMP_BAD 0 #endif #include <string.h> #include <errno.h> #if !AC_BUILT || HAVE_FCNTL_H #include <fcntl.h> #endif #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include "aes.h" #include "md5.h" #include "sha.h" #include "openssl_code.h" #include "arch.h" #include "misc.h" #include "params.h" #include "common.h" #include "formats.h" #include "jumbo.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 8 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "openssl-enc" #define FORMAT_NAME "OpenSSL \"enc\" encryption" #define ALGORITHM_NAME "32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 8 #define MAX_KEYS_PER_CRYPT 8 #define PLAINTEXT_LENGTH 125 #define FORMAT_TAG "$openssl$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked; static struct custom_salt { unsigned int saltlen; unsigned char salt[16]; int cipher; int md; int inlined; int kpa; int datalen; unsigned char kpt[256]; unsigned char data[1024]; unsigned char last_chunks[32]; } *cur_salt; static struct fmt_tests tests[] = { {"$openssl$1$0$8$a1a5e529c8d92da5$8de763bf61377d365243993137ad9729$1$0", "password"}, {"$openssl$1$1$8$844527fb2f5d7ad5$ebccb1fcd2b1b30c5c3624d4016978ea$1$0", "password"}, {"$openssl$0$0$8$305cedc2a0521011$bf11609a01e78ec3f50f0cc483e636f9$1$0", "password"}, {"$openssl$0$0$8$305cedc2a0521011$bf11609a01e78ec3f50f0cc483e636f9$1$1$123456", "password"}, {"$openssl$0$0$8$3993671be477e8f0$95384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$0$256$9bbbc2af64ba27444370e3b3db6f4077a5b83c099a9b0a13d0c03dbc89185aad078266470bb15c44e7b35aef66f456ba7f44fb0f60824331f5b598347cd471c6745374c7dbecf49a1dd0378e938bb9d3d68703e3038805fb3c7bf0623222bcc8e9375b10853aa7c991ddd086b8e2a97dd9ddd351ee0facde9bc3529742f0ffab990db046f5a64765d7a4b1c83b0290acae3eaa09278933cddcf1fed0ab14d408cd43fb73d830237dcd681425cd878bf4b542c108694b90e82f912c4aa4de02bd002dce975c2bb308aad933bfcfd8375d91837048d110f007ba3852dbb498a54595384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$0", "password"}, {"$openssl$0$0$8$3993671be477e8f0$95384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$0$256$9bbbc2af64ba27444370e3b3db6f4077a5b83c099a9b0a13d0c03dbc89185aad078266470bb15c44e7b35aef66f456ba7f44fb0f60824331f5b598347cd471c6745374c7dbecf49a1dd0378e938bb9d3d68703e3038805fb3c7bf0623222bcc8e9375b10853aa7c991ddd086b8e2a97dd9ddd351ee0facde9bc3529742f0ffab990db046f5a64765d7a4b1c83b0290acae3eaa09278933cddcf1fed0ab14d408cd43fb73d830237dcd681425cd878bf4b542c108694b90e82f912c4aa4de02bd002dce975c2bb308aad933bfcfd8375d91837048d110f007ba3852dbb498a54595384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$1$00000000", "password"}, // natalya.aes-256-cbc {"$openssl$0$2$8$8aabc4a37e4b6247$0135d41c5a82a620e3adac2a3d4f1358d1aa6c747811f98bdfb29157d2b39a55$0$240$65fdecc46300f543bdf4607ccc4e9117da5ab3b6978e98226c1283cb48701dbc2e1ac7593718f363dc381f244e7a404c8a7ff581aa93b702bebf55ed1c8a82fb629830d792053a132cbaeb51292b258d38fb349385af592a94acded393dfb75bc21874e65498360d93d031725028a9e9b0f8edcfcd89c2a4e88784a24712895fca4f463e2089ef7db580d7841301c1d63c640fd79e9d6c0ad3b4fc94fe610eb5f29400e883027e0469537e79c3ee1ae2cd3250b825288c4373c45f5ea6f6f1236681c55bcc4f1eb137c221bb3f42a0480135d41c5a82a620e3adac2a3d4f1358d1aa6c747811f98bdfb29157d2b39a55$1$privkey", "knockers"}, {NULL} }; static void init(struct fmt_main *self) { #if defined (_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)); cracked = mem_calloc(self->params.max_keys_per_crypt, sizeof(*cracked)); } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } //#define DEBUG_VALID #ifdef DEBUG_VALID // Awesome debug macro for valid() #define return if (printf("\noriginal: %s\n",ciphertext)+printf("fail line %u: '%s' p=%p q=%p q-p-1=%u\n",__LINE__,p,p,q,(unsigned int)(q-p-1)))return #endif static int valid(char *ciphertext, struct fmt_main *self) { char *p = ciphertext, *q = NULL; int len; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0) return 0; p += TAG_LENGTH; // cipher q = strchr(p, '$'); if (!q) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; p = q; q = strchr(p, '$'); // md if (!q) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1' && *p !='2') return 0; p = q; q = strchr(p, '$'); // salt-size if (!q) return 0; q = q + 1; len = strspn(p, DIGITCHARS); if (len < 1 || len > 2 || len != q - p - 1) return 0; len = atoi(p); if (len < 1 || len > sizeof(cur_salt->salt)) return 0; p = q; q = strchr(p, '$'); // salt if (!q) return 0; q = q + 1; if (2 * len != q - p - 1 || 2 * len != strspn(p, HEXCHARS_lc)) return 0; p = q; q = strchr(p, '$'); // last-chunks if (!q) return 0; q = q + 1; len = strspn(p, HEXCHARS_lc); if (len != q - p - 1 || len < 2 || (len & 1) || len/2 > sizeof(cur_salt->last_chunks)) return 0; p = q; q = strchr(p, '$'); // inlined if (!q) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; if (*p == '0') { p = q; q = strchr(p, '$'); // datalen if (!q) return 0; q = q + 1; len = strspn(p, DIGITCHARS); if (len < 1 || len > 3 || len != q - p - 1) return 0; len = atoi(p); if (len < 1 || len > sizeof(cur_salt->data)) return 0; p = q; q = strchr(p, '$'); // data if (!q) return 0; q = q + 1; if (2 * len != q - p - 1 || 2 * len != strspn(p, HEXCHARS_all)) return 0; } p = q; q = strchr(p, '$'); // known-plaintext if (!q) return !strcmp(p, "0"); if (strlen(q) == 1) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; if (strlen(q) > sizeof(cur_salt->kpt) - 1) return 0; #ifdef DEBUG_VALID #undef return #endif return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i, res; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += TAG_LENGTH; p = strtokm(ctcopy, "$"); cs.cipher = atoi(p); p = strtokm(NULL, "$"); cs.md = atoi(p); p = strtokm(NULL, "$"); cs.saltlen = atoi(p); p = strtokm(NULL, "$"); for (i = 0; i < cs.saltlen; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); res = strlen(p) / 2; for (i = 0; i < res; i++) cs.last_chunks[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); cs.inlined = atoi(p); if (cs.inlined) { p = strtokm(NULL, "$"); cs.kpa = atoi(p); if (cs.kpa) { p = strtokm(NULL, "$"); strncpy((char*)cs.kpt, p, 255); } } else { p = strtokm(NULL, "$"); cs.datalen = atoi(p); p = strtokm(NULL, "$"); for (i = 0; i < cs.datalen; i++) cs.data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); cs.kpa = atoi(p); if (cs.kpa) { p = strtokm(NULL, "$"); strncpy((char*)cs.kpt, p, 255); } } MEM_FREE(keeptr); return (void *)&cs; } static int kpa(unsigned char *key, unsigned char *iv, int inlined) { AES_KEY akey; unsigned char out[1024]; if (AES_set_decrypt_key(key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } if (inlined) { AES_cbc_encrypt(cur_salt->last_chunks, out, 16, &akey, iv, AES_DECRYPT); if (memmem(out, 16, cur_salt->kpt, strlen((char*)cur_salt->kpt))) return 0; } else { AES_cbc_encrypt(cur_salt->data, out, cur_salt->datalen, &akey, iv, AES_DECRYPT); if (memmem(out, cur_salt->datalen, cur_salt->kpt, strlen((char*)cur_salt->kpt))) return 0; } return -1; } static int decrypt(char *password) { unsigned char out[16]; AES_KEY akey; unsigned char iv[16]; unsigned char biv[16]; unsigned char key[32]; int nrounds = 1; // Seems to be fixed as of OpenSSL 1.1.0e (July, 2017) // FIXME handle more stuff switch(cur_salt->cipher) { case 0: switch(cur_salt->md) { case 0: BytesToKey(256, md5, cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 256, &akey); break; case 1: BytesToKey(256, sha1, cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 256, &akey); break; case 2: BytesToKey(256, sha256, cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 256, &akey); break; } break; case 1: switch(cur_salt->md) { case 0: BytesToKey(128, md5, cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 128, &akey); break; case 1: BytesToKey(128, sha1, cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 128, &akey); break; case 2: BytesToKey(128, sha256, cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 128, &akey); break; } break; } memcpy(biv, iv, 16); if (cur_salt->inlined) AES_cbc_encrypt(cur_salt->last_chunks, out, 16, &akey, iv, AES_DECRYPT); else { memcpy(iv, cur_salt->last_chunks, 16); AES_cbc_encrypt(cur_salt->last_chunks + 16, out, 16, &akey, iv, AES_DECRYPT); } // now check padding if (check_pkcs_pad(out, 16, 16) < 0) return -1; if (cur_salt->kpa) return kpa(key, biv, cur_salt->inlined); return 0; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { if (decrypt(saved_key[index]) == 0) cracked[index] = 1; else cracked[index] = 0; } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_openssl = { { 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 | FMT_NOT_EXACT, /* * FIXME: if there wouldn't be so many false positives, * it would be useful to report some tunable costs */ { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
statistic.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImage method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ typedef struct _PixelChannels { double channel[CompositePixelChannel]; } PixelChannels; static PixelChannels **DestroyPixelThreadSet(PixelChannels **pixels) { register ssize_t i; assert(pixels != (PixelChannels **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (PixelChannels *) NULL) pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]); pixels=(PixelChannels **) RelinquishMagickMemory(pixels); return(pixels); } static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const PixelChannels *color_1, *color_2; double distance; register ssize_t i; color_1=(const PixelChannels *) x; color_2=(const PixelChannels *) y; distance=0.0; for (i=0; i < MaxPixelChannels; i++) distance+=color_1->channel[i]-(double) color_2->channel[i]; return(distance < 0 ? -1 : distance > 0 ? 1 : 0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel, const MagickEvaluateOperator op,const double value) { double result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(double) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(double) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() that returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(double) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise, value); break; } case LaplacianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(double) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+ 1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(double) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(double) (pixel+value); break; } case MedianEvaluateOperator: { result=(double) (pixel+value); break; } case MinEvaluateOperator: { result=(double) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(double) (value*pixel); break; } case OrEvaluateOperator: { result=(double) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise, value); break; } case PowEvaluateOperator: { result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),(double) value)); break; } case RightShiftEvaluateOperator: { result=(double) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(double) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(double) (pixel-value); break; } case SumEvaluateOperator: { result=(double) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(double) (((double) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise, value); break; } case XorEvaluateOperator: { result=(double) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, rows; q=images; columns=images->columns; rows=images->rows; for (p=images; p != (Image *) NULL; p=p->next) { if (p->number_channels > q->number_channels) q=p; if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict evaluate_pixels; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j, k; for (j=0; j < (ssize_t) number_images; j++) for (k=0; k < MaxPixelChannels; k++) evaluate_pixel[j].channel[k]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; register ssize_t i; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); PixelTrait traits = GetPixelChannelTraits(next,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[j].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),op, evaluate_pixel[j].channel[i]); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); for (k=0; k < (ssize_t) GetPixelChannels(image); k++) q[k]=ClampToQuantum(evaluate_pixel[j/2].channel[k]); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImages) #endif proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) evaluate_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(next,p) <= (QuantumRange/2)) { p+=GetPixelChannels(next); continue; } for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[x].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),j == 0 ? AddEvaluateOperator : op,evaluate_pixel[x].channel[i]); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; switch (op) { case MeanEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]/=(double) number_images; break; } case MultiplyEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) evaluate_pixel[x].channel[i]*=QuantumScale; } break; } case RootMeanSquareEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/ number_images); break; } default: break; } } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImages) #endif proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double result; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if (((traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,q) <= (QuantumRange/2))) continue; if ((traits & UpdatePixelTrait) == 0) continue; result=ApplyEvaluateOperator(random_info[id],q[i],op,value); if (op == MeanEvaluateOperator) result/=2.0; q[i]=ClampToQuantum(result); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImage) #endif proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImage method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { double result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+ c1*x^2+c2*x+c3). */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel+parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { double amplitude, bias, frequency, phase; /* Sinusoid: frequency, phase, amplitude, bias. */ frequency=(number_parameters >= 1) ? parameters[0] : 1.0; phase=(number_parameters >= 2) ? parameters[1] : 0.0; amplitude=(number_parameters >= 3) ? parameters[2] : 0.5; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (QuantumRange*(amplitude*sin((double) (2.0* MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias)); break; } case ArcsinFunction: { double bias, center, range, width; /* Arcsin (peged at range limits for invalid results): width, center, range, and bias. */ width=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=2.0/width*(QuantumScale*pixel-center); if ( result <= -1.0 ) result=bias-range/2.0; else if (result >= 1.0) result=bias+range/2.0; else result=(double) (range/MagickPI*asin((double) result)+bias); result*=QuantumRange; break; } case ArctanFunction: { double center, bias, range, slope; /* Arctan: slope, center, range, and bias. */ slope=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (MagickPI*slope*(QuantumScale*pixel-center)); result=(double) (QuantumRange*(range/MagickPI*atan((double) result)+bias)); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateFunctionImage(image,function,number_parameters,parameters, exception) != MagickFalse) return(MagickTrue); #endif if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyFunction(q[i],function,number_parameters,parameters, exception); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FunctionImage) #endif proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageEntropy() returns the entropy of one or more image channels. % % The format of the GetImageEntropy method is: % % MagickBooleanType GetImageEntropy(const Image *image,double *entropy, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *entropy=channel_statistics[CompositePixelChannel].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtrema() returns the extrema of one or more image channels. % % The format of the GetImageExtrema method is: % % MagickBooleanType GetImageExtrema(const Image *image,size_t *minima, % size_t *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageRange(image,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageKurtosis() returns the kurtosis and skewness of one or more image % channels. % % The format of the GetImageKurtosis method is: % % MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis, % double *skewness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *kurtosis=channel_statistics[CompositePixelChannel].kurtosis; *skewness=channel_statistics[CompositePixelChannel].skewness; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMean() returns the mean and standard deviation of one or more image % channels. % % The format of the GetImageMean method is: % % MagickBooleanType GetImageMean(const Image *image,double *mean, % double *standard_deviation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *mean=channel_statistics[CompositePixelChannel].mean; *standard_deviation= channel_statistics[CompositePixelChannel].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageMoments method is: % % ChannelMoments *GetImageMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; channels++; } return((size_t) (channels == 0 ? 1 : channels)); } MagickExport ChannelMoments *GetImageMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 CacheView *image_view; ChannelMoments *channel_moments; double M00[MaxPixelChannels+1], M01[MaxPixelChannels+1], M02[MaxPixelChannels+1], M03[MaxPixelChannels+1], M10[MaxPixelChannels+1], M11[MaxPixelChannels+1], M12[MaxPixelChannels+1], M20[MaxPixelChannels+1], M21[MaxPixelChannels+1], M22[MaxPixelChannels+1], M30[MaxPixelChannels+1]; PointInfo centroid[MaxPixelChannels+1]; ssize_t channel, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,(MaxPixelChannels+1)* sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M00[channel]+=QuantumScale*p[i]; M00[MaxPixelChannels]+=QuantumScale*p[i]; M10[channel]+=x*QuantumScale*p[i]; M10[MaxPixelChannels]+=x*QuantumScale*p[i]; M01[channel]+=y*QuantumScale*p[i]; M01[MaxPixelChannels]+=y*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } M00[MaxPixelChannels]/=GetImageChannels(image); M01[MaxPixelChannels]/=GetImageChannels(image); M02[MaxPixelChannels]/=GetImageChannels(image); M03[MaxPixelChannels]/=GetImageChannels(image); M10[MaxPixelChannels]/=GetImageChannels(image); M11[MaxPixelChannels]/=GetImageChannels(image); M12[MaxPixelChannels]/=GetImageChannels(image); M20[MaxPixelChannels]/=GetImageChannels(image); M21[MaxPixelChannels]/=GetImageChannels(image); M22[MaxPixelChannels]/=GetImageChannels(image); M30[MaxPixelChannels]/=GetImageChannels(image); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } image_view=DestroyCacheView(image_view); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].invariant[0]=M20[channel]+M02[channel]; channel_moments[channel].invariant[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].invariant[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].invariant[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].invariant[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].invariant[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[7]=M11[channel]*((M30[channel]+ M12[channel])*(M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImagePerceptualHash method is: % % ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, ExceptionInfo *exception) { ChannelPerceptualHash *perceptual_hash; char *colorspaces, *q; const char *artifact; MagickBooleanType status; register char *p; register ssize_t i; perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( MaxPixelChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); artifact=GetImageArtifact(image,"phash:colorspaces"); if (artifact != NULL) colorspaces=AcquireString(artifact); else colorspaces=AcquireString("sRGB,HCLp"); perceptual_hash[0].number_colorspaces=0; perceptual_hash[0].number_channels=0; q=colorspaces; for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++) { ChannelMoments *moments; Image *hash_image; size_t j; ssize_t channel, colorspace; if (i >= MaximumNumberOfPerceptualColorspaces) break; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p); if (colorspace < 0) break; perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace; hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) break; hash_image->depth=8; status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace, exception); if (status == MagickFalse) break; moments=GetImageMoments(hash_image,exception); perceptual_hash[0].number_colorspaces++; perceptual_hash[0].number_channels+=GetImageChannels(hash_image); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) break; for (channel=0; channel <= MaxPixelChannels; channel++) for (j=0; j < MaximumNumberOfImageMoments; j++) perceptual_hash[channel].phash[i][j]= (-MagickLog10(moments[channel].invariant[j])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); } colorspaces=DestroyString(colorspaces); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageRange() returns the range of one or more image channels. % % The format of the GetImageRange method is: % % MagickBooleanType GetImageRange(const Image *image,double *minima, % double *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima, double *maxima,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType initialize, status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; initialize=MagickTrue; *maxima=0.0; *minima=0.0; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,initialize) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double row_maxima = 0.0, row_minima = 0.0; MagickBooleanType row_initialize; register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } row_initialize=MagickTrue; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (row_initialize != MagickFalse) { row_minima=(double) p[i]; row_maxima=(double) p[i]; row_initialize=MagickFalse; } else { if ((double) p[i] < row_minima) row_minima=(double) p[i]; if ((double) p[i] > row_maxima) row_maxima=(double) p[i]; } } p+=GetPixelChannels(image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageRange) #endif { if (initialize != MagickFalse) { *minima=row_minima; *maxima=row_maxima; initialize=MagickFalse; } else { if (row_minima < *minima) *minima=row_minima; if (row_maxima > *maxima) *maxima=row_maxima; } } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageStatistics() returns statistics for each channel in the image. The % statistics include the channel depth, its minima, maxima, mean, standard % deviation, kurtosis and skewness. You can access the red channel mean, for % example, like this: % % channel_statistics=GetImageStatistics(image,exception); % red_mean=channel_statistics[RedPixelChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageStatistics method is: % % ChannelStatistics *GetImageStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, *histogram, standard_deviation; MagickStatusType status; QuantumAny range; register ssize_t i; size_t depth; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); channel_statistics=(ChannelStatistics *) AcquireQuantumMemory( MaxPixelChannels+1,sizeof(*channel_statistics)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (double *) NULL)) { if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,(MaxPixelChannels+1)* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[channel].depth; range=GetQuantumRange(depth); status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range), range) ? MagickTrue : MagickFalse; if (status != MagickFalse) { channel_statistics[channel].depth++; i--; continue; } } if ((double) p[i] < channel_statistics[channel].minima) channel_statistics[channel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[channel].maxima) channel_statistics[channel].maxima=(double) p[i]; channel_statistics[channel].sum+=p[i]; channel_statistics[channel].sum_squared+=(double) p[i]*p[i]; channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]* p[i]; channel_statistics[channel].area++; if ((double) p[i] < channel_statistics[CompositePixelChannel].minima) channel_statistics[CompositePixelChannel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima) channel_statistics[CompositePixelChannel].maxima=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum((double) p[i]))+i]++; channel_statistics[CompositePixelChannel].sum+=(double) p[i]; channel_statistics[CompositePixelChannel].sum_squared+=(double) p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].area++; } p+=GetPixelChannels(image); } } for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Normalize pixel statistics. */ area=PerceptibleReciprocal(channel_statistics[i].area); channel_statistics[i].sum*=area; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=channel_statistics[i].sum; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area- 1.0)*channel_statistics[i].area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double number_bins; register ssize_t j; /* Compute pixel entropy. */ PixelChannel channel = GetPixelChannelChannel(image,i); number_bins=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) if (histogram[GetPixelChannels(image)*j+i] > 0.0) number_bins++; area=PerceptibleReciprocal(channel_statistics[channel].area); for (j=0; j <= (ssize_t) MaxMap; j++) { double count; count=area*histogram[GetPixelChannels(image)*j+i]; channel_statistics[channel].entropy+=-count*MagickLog10(count)* PerceptibleReciprocal(MagickLog10(number_bins)); channel_statistics[CompositePixelChannel].entropy+=-count* MagickLog10(count)*PerceptibleReciprocal(MagickLog10(number_bins))/ GetPixelChannels(image); } } histogram=(double *) RelinquishMagickMemory(histogram); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositePixelChannel].mean=0.0; channel_statistics[CompositePixelChannel].standard_deviation=0.0; channel_statistics[CompositePixelChannel].entropy=0.0; for (i=0; i < (ssize_t) MaxPixelChannels; i++) { channel_statistics[CompositePixelChannel].mean+= channel_statistics[i].mean; channel_statistics[CompositePixelChannel].standard_deviation+= channel_statistics[i].standard_deviation; channel_statistics[CompositePixelChannel].entropy+= channel_statistics[i].entropy; } channel_statistics[CompositePixelChannel].mean/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].standard_deviation/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].entropy/=(double) GetImageChannels(image); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict polynomial_pixels; size_t number_images; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *polynomial_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } polynomial_pixel=polynomial_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) polynomial_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; if (j >= (ssize_t) number_terms) continue; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(next,p) <= (QuantumRange/2)) { p+=GetPixelChannels(next); continue; } for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { MagickRealType coefficient, degree; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (polynomial_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; coefficient=(MagickRealType) terms[2*j]; degree=(MagickRealType) terms[(j << 1)+1]; polynomial_pixel[x].channel[i]+=coefficient* pow(QuantumScale*GetPixelChannel(image,channel,p),degree); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PolynomialImages) #endif proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ typedef struct _SkipNode { size_t next[9], count, signature; } SkipNode; typedef struct _SkipList { ssize_t level; SkipNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed; SkipList skip_list; size_t signature; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); if (pixel_list->skip_list.nodes != (SkipNode *) NULL) pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory( pixel_list->skip_list.nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->skip_list.nodes)); if (pixel_list->skip_list.nodes == (SkipNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->skip_list.nodes,0,65537UL* sizeof(*pixel_list->skip_list.nodes)); pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const size_t color) { register SkipList *p; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ p=(&pixel_list->skip_list); p->nodes[color].signature=pixel_list->signature; p->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=p->level; level >= 0; level--) { while (p->nodes[search].next[level] < color) search=p->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (p->level+2)) level=p->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > p->level) { p->level++; update[p->level]=65536UL; } /* Link the node into the skip-list. */ do { p->nodes[color].next[level]=p->nodes[update[level]].next[level]; p->nodes[update[level]].next[level]=color; } while (level-- > 0); } static inline void GetMaximumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, maximum; ssize_t count; /* Find the maximum value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; maximum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color > maximum) maximum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) maximum); } static inline void GetMeanPixelList(PixelList *pixel_list,Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the mean value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sum); } static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color; ssize_t count; /* Find the median value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; do { color=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetMinimumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, minimum; ssize_t count; /* Find the minimum value for each of the color. */ p=(&pixel_list->skip_list); count=0; color=65536UL; minimum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color < minimum) minimum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) minimum); } static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, max_count, mode; ssize_t count; /* Make each pixel the 'predominant color' of the specified neighborhood. */ p=(&pixel_list->skip_list); color=65536L; mode=color; max_count=p->nodes[mode].count; count=0; do { color=p->nodes[color].next[0]; if (p->nodes[color].count > max_count) { mode=color; max_count=p->nodes[mode].count; } count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) mode); } static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, next, previous; ssize_t count; /* Finds the non peak value for each of the colors. */ p=(&pixel_list->skip_list); color=65536L; next=p->nodes[color].next[0]; count=0; do { previous=color; color=next; next=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetRootMeanSquarePixelList(PixelList *pixel_list, Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the root mean square value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) (p->nodes[color].count*color*color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum)); } static inline void GetStandardDeviationPixelList(PixelList *pixel_list, Quantum *pixel) { double sum, sum_squared; register SkipList *p; size_t color; ssize_t count; /* Find the standard-deviation value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; for (i=0; i < (ssize_t) p->nodes[color].count; i++) sum_squared+=((double) color)*((double) color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum_squared-(sum*sum))); } static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(pixel); signature=pixel_list->skip_list.nodes[index].signature; if (signature == pixel_list->signature) { pixel_list->skip_list.nodes[index].count++; return; } AddNodePixelList(pixel_list,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register SkipNode *root; register SkipList *p; /* Reset the skip-list. */ p=(&pixel_list->skip_list); root=p->nodes+65536UL; p->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; ssize_t center, y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(statistic_image,DirectClass,exception); if (status == MagickFalse) { statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1)); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))* (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y- (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1), MagickMax(height,1),exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) statistic_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { Quantum pixel; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image, channel); if ((traits == UndefinedPixelTrait) || (statistic_traits == UndefinedPixelTrait)) continue; if (((statistic_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,p) <= (QuantumRange/2))) { SetPixelChannel(statistic_image,channel,p[center+i],q); continue; } if ((statistic_traits & UpdatePixelTrait) == 0) continue; pixels=p; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) MagickMax(height,1); v++) { for (u=0; u < (ssize_t) MagickMax(width,1); u++) { InsertPixelList(pixels[i],pixel_list[id]); pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } switch (type) { case GradientStatistic: { double maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=(double) pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=(double) pixel; pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum)); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } SetPixelChannel(statistic_image,channel,pixel,q); } p+=GetPixelChannels(image); q+=GetPixelChannels(statistic_image); } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_StatisticImage) #endif proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
mini.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <omp.h> typedef struct { long long int re; long long int im; } com; typedef struct { com x; com y; } PO; typedef struct { unsigned int p; unsigned int e2; unsigned int e3; unsigned int xQ20; unsigned int xQ21; unsigned int yQ20; unsigned int yQ21; unsigned int xP20; unsigned int xP21; unsigned int yP20; unsigned int yP21; unsigned int xR20; unsigned int xR21; unsigned int xQ30; unsigned int xQ31; unsigned int yQ30; unsigned int yQ31; unsigned int xP30; unsigned int xP31; unsigned int yP30; unsigned int yP31; unsigned int xR30; unsigned int xR31; unsigned int n; } SIDH; typedef struct { int n; int p; int q; char s[]; } tor; typedef struct { unsigned int p; unsigned int e2; unsigned int e3; PO P2; PO P3; PO Q2; PO Q3; PO R2; PO R3; unsigned int n; } CM; unsigned int p=431; unsigned int pp=185761; // SIDH sp434; // invert of integer long long int inv(long long int a,long long int n){ long long int d,x,s,q,r,t; d = n; x = 0; s = 1; while (a != 0){ q = d / a; r = d % a; d = a; a = r; t = x - q * s; x = s; s = t; } // gcd = d; // $\gcd(a, n)$ return ((x + n) % (n / d)); } //SIDH com cadd(com a,com b){ com c; c.re=(a.re+b.re); if(c.re>p) c.re=c.re%p; if(c.re<0) c.re+=p; c.im=(a.im+b.im); if(c.im>p) c.im=c.im%p; if(c.im<0) c.im=c.im+p; return c; } com inv_add(com a){// -a com c; c.re= -1; c.im= -1; c.re=c.re*a.re%p; if(c.re>p) c.re%=p; c.im=c.im*a.im%p; if(c.im>p) c.im%=p; return c; } com csub(com a,com b){ com c,m; c.re=(a.re-b.re); if(c.re<0) c.re+=p; c.im=(a.im-b.im); if(c.im<0) c.im+=p; return c; } com cmul(com a,com b){ com c; long long int d,e; c.re=a.re*b.re-(a.im*b.im); d=(a.re*b.im);//%p; e=(b.re*a.im);//%p; // c.re=c.re+c.im;//%p; c.im=d+e;//%p; return c; } com cinv(com a){ com c,a1,a2,b1,b2,h,w; unsigned int i,j,d,e,f,g,A,pp,l,n; for(l=0;l<p;l++){ //#pragma omp parallel for for(n=0;n<p;n++){ //a=162+172i //a2.re=162; //a2.im=172; a2.re=l; //259 a2.im=n; //340 b1=cmul(a2,a); if(b1.re%p==1 && b1.im%p==0){ printf("%d %d %d %d\n",a1.re,a1.im,b1.re%p,b1.im%p); printf("%d %d\n",l,n); // exit(1); return a2; } } } return a2; } com cdiv(com a,com b){ com c,d,v,f,h; long long g; d.re=(b.re*b.re+b.im*b.im)%p; if(d.re>p) d.re=d.re%p; if(d.re<0) d.re=d.re+p; d.im=0; v.re=((a.re%p)*(b.re%p)+((a.im%p)*(b.im%p))%p)%p; v.im=((a.im%p)*(b.re%p))-(a.re%p)*(b.im%p); if(a.re>p) a.re=a.re%p; if(a.re<0) a.re=b.re+p; if(a.im>p) a.im=b.im%p; if(a.im<0) a.re=a.im+p; if(b.re>p) b.re=a.re%p; if(b.re<0) b.re=b.re+p; if(b.im>p) b.im=b.im%p; if(b.im<0) b.re=a.im+p; printf("re=%lld %lld\n",a.re,b.re); printf("imm=%lldi %lldi\n",a.im,b.im); //exit(1); printf("d=%lld\n",d.re); d.re=inv(d.re,p); v.re=((p+v.re)*d.re)%p; v.im=((v.im%p)*d.re)%p; if(v.re>p) v.re=v.re%p; if(v.im<0) v.im+=p; printf("v=%lld %lldi\n",v.re,v.im); // exit(1); //c.re=d.re; //c.im=v.im*inv(d.re,p); return v; } com cnst(unsigned int A,com a){ unsigned int t,s; com r; t=A*a.re; s=A*a.im; r.re=t; r.im=s; return r; } PO eadd(PO P,PO Q){ PO R={0}; unsigned int r,s,t,u,v,w; com c,d,e,f,g,l,A; A.re=6; A.im=0; c=csub(P.y,Q.y); d=csub(P.x,Q.x); e=cinv(d); l=cmul(c,e); d=cmul(l,l); e=cadd(P.x,Q.x); R.x=csub(csub(d,e),A); R.y=csub(cmul(l,csub(P.x,R.x)),P.y); return R; } PO eadd2(PO P){ com a,b,c; PO R; return R; } //E = EllipticCurve(GF(131), [0, 0, 0, 1, 23]) //E.j_invariant() com j_inv(com a){ com r,f,h,b1,b2,h1,o,g,q; // unsigned int w; o.re= 3; o.im= 0; q.re= 256; q.im= 0; f.re=4; f.im=0; r=cmul(a,a); //printf("%d %d\n",r.re,r.im); //a^2-4 h=csub(r,f); printf("a^2-4: %lld %lld\n",h.re,h.im); b1=cadd(r,f); printf("%lld %lld\n",b1.re,b1.im); b2=cmul(r,r); h1=cmul(f,f); h1=cadd(h1,b2); printf("%lld %lld\n",h1.re,h1.im); //p=131 のとき y^2 = x^3 + x + 23 の j-不変量は 78 となります。 //g=a^2-3 g=csub(r,o); printf("a^2-3: %d %d\n",g.re,g.im); printf("a^2-4: %lld %lld\n",h.re,h.im); //g=256*(a^2-3)^3 //(a^2 - 3)^2 = -4184900860 - 2323531392 I //(a^2 - 3)^3 = 228212128828152 - 239983944473728 I g=cmul(cmul(cmul(g,g),g),q); g.re=g.re%p; g.im=g.im%p; printf("g=256*(a^2-3)^3: %lld %lld\n",g.re,g.im); g=cdiv(g,h); if(g.re>p) g.re%=p; if(g.re<0) g.re+=p; if(g.im>p) g.im=g.im%p; if(g.im<0) g.im+=p; printf("ans=%lld,%lld\n",g.re,g.im); return g; } /* //jj=aa^bb mod oo BigInt exp(BigInt aa,BigInt bb,BigInt oo){ BigInt ii,jj,kk[8192]; int j,c[8192],count=0,i; ii=oo; j=0; jj=0; // kk[4096]; //prime is 4096 bit table // c[8192] //mod is 8192 bit table count=0; for(i=0;i<8192;i++){ kk[i]=0; } while(ii>0){ ii = (ii>>1); j=j+1; } kk[0]=aa; // std::cout << j << "\n"; //ex.1000=2**3+2**5+2**6+2**7+2**8+2**9 makes a array c=[3,5,6,7,8,9] for(i=0;i<j+1;i++){ if((bb >> i)%2 != 0){ // testbit(bb,i) c[count]=i; count=count+1; } } // std::cout << bb << endl; // std::cout << count << "\n"; //exit(1); for(i=1;i<c[count-1]+1;i++){ kk[i] = kk[i-1]*kk[i-1]%oo; } jj=1; for(i=0;i<count;i++){ jj=kk[c[i]]*jj%oo; if (jj==0){ // print i,"\n" } } return jj; } */ com cc(com a,com b){ com c; c.re= a.re*b.re+a.im*b.im; c.im=0; return c; } int main () { char buf[65536]; CM sp434; com a1,a2,b1,b2,j,r,o,q,g,f,v,w,h,r2,g2,h2,h1,c; int s=31,t=304,l,k,n,i,count=0,a,b,jj,aa,bb,jj2; s=inv(s,p); //a1 v.re=s; v.im=0; t=inv(t,p); //a2 w.re=s; w.im=0; printf("s=%d,t=%d\n",s,t); o.re= 3; o.im= 0; q.re= 256; q.im= 0; f.re=4; f.im=0; //h.re=p; //h.im=0; //q=cdiv(r,o); //printf("%d %d\n",q.re,q.im); //exit(1); //a=161+208i a1.re=161; a1.im=208; j_inv(a1); printf("a1======================================\n"); //exit(1); a2.re=161; //162; a2.im=208;//172; a2=j_inv(a2); printf("j=%d %d\n",a2.re,a2.im); //exit(1); //同じj不変量を持つ楕円曲線を総探索する 20200804 for(i=0;i<p;i++){ o.re=i; for(k=0;k<p;k++){ o.im=k; r=j_inv(o); //scanf("%d",&n); if(r.re==304 && r.im==364){ printf("(i,k)=%d %d\n",i,k); count++; } /* if(i==161 && k==208){ printf("??\n"); exit(1); } */ } } printf("p=%d count=%d\n",p,count); return 0; }
ewald.h
#ifndef ewald_h #define ewald_h #include "logger.h" #include "types.h" namespace exafmm { class Ewald { //! Wave structure for Ewald summation struct Wave { vec3 K; //!< 3-D wave number vector real_t REAL; //!< real part of wave real_t IMAG; //!< imaginary part of wave }; typedef std::vector<Wave> Waves; //!< Vector of Wave types typedef Waves::iterator W_iter; //!< Iterator of Wave types private: const int ksize; //!< Number of waves in Ewald summation const real_t alpha; //!< Scaling parameter for Ewald summation const real_t sigma; //!< Scaling parameter for Ewald summation const real_t cutoff; //!< Cutoff distance const vec3 cycle; //!< Periodic cycle private: //! Forward DFT void dft(Waves & waves, Bodies & bodies) const { vec3 scale; for (int d=0; d<3; d++) scale[d]= 2 * M_PI / cycle[d]; // Scale conversion #pragma omp parallel for for (int w=0; w<int(waves.size()); w++) { // Loop over waves W_iter W=waves.begin()+w; // Wave iterator W->REAL = W->IMAG = 0; // Initialize waves for (B_iter B=bodies.begin(); B!=bodies.end(); B++) { // Loop over bodies real_t th = 0; // Initialize phase for (int d=0; d<3; d++) th += W->K[d] * B->X[d] * scale[d];// Determine phase W->REAL += B->SRC * std::cos(th); // Accumulate real component W->IMAG += B->SRC * std::sin(th); // Accumulate imaginary component } // End loop over bodies } // End loop over waves } //! Inverse DFT void idft(Waves & waves, Bodies & bodies) const { vec3 scale; for (int d=0; d<3; d++) scale[d] = 2 * M_PI / cycle[d]; // Scale conversion #pragma omp parallel for for (int b=0; b<int(bodies.size()); b++) { // Loop over bodies B_iter B=bodies.begin()+b; // Body iterator kvec4 TRG = kreal_t(0); // Initialize target values for (W_iter W=waves.begin(); W!=waves.end(); W++) { // Loop over waves real_t th = 0; // Initialzie phase for (int d=0; d<3; d++) th += W->K[d] * B->X[d] * scale[d];// Determine phase real_t dtmp = W->REAL * std::sin(th) - W->IMAG * std::cos(th);// Temporary value TRG[0] += W->REAL * std::cos(th) + W->IMAG * std::sin(th);// Accumulate potential for (int d=0; d<3; d++) TRG[d+1] -= dtmp * W->K[d]; // Accumulate force } // End loop over waves for (int d=0; d<3; d++) TRG[d+1] *= scale[d]; // Scale forces B->TRG += TRG; // Copy results to bodies } // End loop over bodies } //! Initialize wave vector Waves initWaves() const { Waves waves; // Initialzie wave vector int kmaxsq = ksize * ksize; // kmax squared int kmax = ksize; // kmax as integer for (int l=0; l<=kmax; l++) { // Loop over x component int mmin = -kmax; // Determine minimum y component if (l==0) mmin = 0; // Exception for minimum y component for (int m=mmin; m<=kmax; m++) { // Loop over y component int nmin = -kmax; // Determine minimum z component if (l==0 && m==0) nmin=1; // Exception for minimum z component for (int n=nmin; n<=kmax; n++) { // Loop over z component real_t ksq = l * l + m * m + n * n; // Wave number squared if (ksq <= kmaxsq) { // If wave number is below kmax Wave wave; // Initialzie wave structure wave.K[0] = l; // x component of k wave.K[1] = m; // y component of k wave.K[2] = n; // z component of k wave.REAL = wave.IMAG = 0; // Initialize amplitude waves.push_back(wave); // Push wave to vector } // End if for wave number } // End loop over z component } // End loop over y component } // End loop over x component return waves; // Return wave vector } //! Ewald real part P2P kernel void P2P(C_iter Ci, C_iter Cj, vec3 Xperiodic) const { for (B_iter Bi=Ci->BODY; Bi!=Ci->BODY+Ci->NBODY; Bi++) { // Loop over target bodies for (B_iter Bj=Cj->BODY; Bj!=Cj->BODY+Cj->NBODY; Bj++) {// Loop over source bodies vec3 dX = Bi->X - Bj->X - Xperiodic; // Distance vector from source to target real_t R2 = norm(dX); // R^2 if (0 < R2 && R2 < cutoff * cutoff) { // Exclude self interaction and cutoff real_t R2s = R2 * alpha * alpha; // (R * alpha)^2 real_t Rs = std::sqrt(R2s); // R * alpha real_t invRs = 1 / Rs; // 1 / (R * alpha) real_t invR2s = invRs * invRs; // 1 / (R * alpha)^2 real_t invR3s = invR2s * invRs; // 1 / (R * alpha)^3 real_t dtmp = Bj->SRC * (M_2_SQRTPI * std::exp(-R2s) * invR2s + erfc(Rs) * invR3s); dtmp *= alpha * alpha * alpha; // Scale temporary value Bi->TRG[0] += Bj->SRC * erfc(Rs) * invRs * alpha; // Ewald real potential Bi->TRG[1] -= dX[0] * dtmp; // x component of Ewald real force Bi->TRG[2] -= dX[1] * dtmp; // y component of Ewald real force Bi->TRG[3] -= dX[2] * dtmp; // z component of Ewald real force } // End if for self interaction } // End loop over source bodies } // End loop over target bodies } //! Recursive functor for traversing tree to find neighbors struct Neighbor { Ewald * ewald; //!< Ewald object C_iter Ci; //!< Iterator of current target cell C_iter Cj; //!< Iterator of current source cell C_iter C0; //!< Iterator of first source cell Neighbor(Ewald * _ewald, C_iter _Ci, C_iter _Cj, C_iter _C0) :// Constructor ewald(_ewald), Ci(_Ci), Cj(_Cj), C0(_C0) {} // Initialize variables void operator() () { // Overload operator() vec3 dX = Ci->X - Cj->X; // Distance vector from source to target wrap(dX, ewald->cycle); // Wrap around periodic domain vec3 Xperiodic = Ci->X - Cj->X - dX; // Coordinate offset for periodic B.C. real_t R = std::sqrt(norm(dX)); // Scalar distance if (R - Ci->R - Cj->R < sqrtf(3) * ewald->cutoff) { // If cells are close if(Cj->NCHILD == 0) ewald->P2P(Ci,Cj,Xperiodic); // Ewald real part for (C_iter CC=C0+Cj->ICHILD; CC!=C0+Cj->ICHILD+Cj->NCHILD; CC++) {// Loop over cell's children Neighbor neighbor(ewald, Ci, CC, C0); // Instantiate recursive functor neighbor(); // Recursive call } // End loop over cell's children } // End if for far cells } // End overload operator() }; public: //! Constructor Ewald(int _ksize, real_t _alpha, real_t _sigma, real_t _cutoff, vec3 _cycle) : ksize(_ksize), alpha(_alpha), sigma(_sigma), cutoff(_cutoff), cycle(_cycle) {} // Initialize variables //! Ewald real part void realPart(Cells & cells, Cells & jcells) { logger::startTimer("Ewald real part"); // Start timer C_iter Cj = jcells.begin(); // Set begin iterator of source cells mk_task_group; // Intitialize tasks for (C_iter Ci=cells.begin(); Ci!=cells.end(); Ci++) { // Loop over target cells if (Ci->NCHILD == 0) { // If target cell is leaf Neighbor neighbor(this, Ci, Cj, Cj); // Instantiate recursive functor create_taskc(neighbor); // Create task for recursive call } // End if for leaf target cell } // End loop over target cells wait_tasks; // Synchronize tasks logger::stopTimer("Ewald real part"); // Stop timer } //! Subtract self term void selfTerm(Bodies & bodies) { for (B_iter B=bodies.begin(); B!=bodies.end(); B++) { // Loop over all bodies B->TRG[0] -= M_2_SQRTPI * B->SRC * alpha; // Self term of Ewald real part } // End loop over all bodies in cell } //! Ewald wave part void wavePart(Bodies & bodies, Bodies & jbodies) { logger::startTimer("Ewald wave part"); // Start timer Waves waves = initWaves(); // Initialize wave vector dft(waves,jbodies); // Apply DFT to bodies to get waves vec3 scale; for (int d=0; d<3; d++) scale[d] = 2 * M_PI / cycle[d]; // Scale conversion real_t coef = 2 / sigma / cycle[0] / cycle[1] / cycle[2]; // First constant real_t coef2 = 1 / (4 * alpha * alpha); // Second constant for (W_iter W=waves.begin(); W!=waves.end(); W++) { // Loop over waves vec3 K = W->K * scale; // Wave number scaled real_t K2 = norm(K); // Wave number squared real_t factor = coef * std::exp(-K2 * coef2) / K2; // Wave factor W->REAL *= factor; // Apply wave factor to real part W->IMAG *= factor; // Apply wave factor to imaginary part } // End loop over waves idft(waves,bodies); // Inverse DFT logger::stopTimer("Ewald wave part"); // Stop timer } void print(int stringLength) { if (logger::verbose) { // If verbose flag is true std::cout << std::setw(stringLength) << std::fixed << std::left// Set format << "ksize" << " : " << ksize << std::endl // Print ksize << std::setw(stringLength) // Set format << "alpha" << " : " << alpha << std::endl // Print alpha << std::setw(stringLength) // Set format << "sigma" << " : " << sigma << std::endl // Print sigma << std::setw(stringLength) // Set format << "cutoff" << " : " << cutoff << std::endl // Print cutoff << std::setw(stringLength) // Set format << "cycle" << " : " << cycle << std::endl; // Print cycle } // End if for verbose flag } }; } #endif
openmp_wrapper.h
/*! * Copyright (c) 2017 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_OPENMP_WRAPPER_H_ #define LIGHTGBM_OPENMP_WRAPPER_H_ #ifdef _OPENMP #include <LightGBM/utils/log.h> #include <omp.h> #include <exception> #include <memory> #include <mutex> #include <stdexcept> #include <vector> inline int OMP_NUM_THREADS() { int ret = 1; #pragma omp parallel #pragma omp master { ret = omp_get_num_threads(); } return ret; } class ThreadExceptionHelper { public: ThreadExceptionHelper() { ex_ptr_ = nullptr; } ~ThreadExceptionHelper() { ReThrow(); } void ReThrow() { if (ex_ptr_ != nullptr) { std::rethrow_exception(ex_ptr_); } } void CaptureException() { // only catch first exception. if (ex_ptr_ != nullptr) { return; } std::unique_lock<std::mutex> guard(lock_); if (ex_ptr_ != nullptr) { return; } ex_ptr_ = std::current_exception(); } private: std::exception_ptr ex_ptr_; std::mutex lock_; }; #define OMP_INIT_EX() ThreadExceptionHelper omp_except_helper #define OMP_LOOP_EX_BEGIN() try { #define OMP_LOOP_EX_END() \ } \ catch (std::exception & ex) { \ Log::Warning(ex.what()); \ omp_except_helper.CaptureException(); \ } \ catch (...) { \ omp_except_helper.CaptureException(); \ } #define OMP_THROW_EX() omp_except_helper.ReThrow() #else #ifdef _MSC_VER #pragma warning(disable : 4068) // disable unknown pragma warning #endif #ifdef __cplusplus extern "C" { #endif /** Fall here if no OPENMP support, so just simulate a single thread running. All #pragma omp should be ignored by the compiler **/ inline void omp_set_num_threads(int) {} inline int omp_get_num_threads() {return 1;} inline int omp_get_thread_num() {return 0;} inline int OMP_NUM_THREADS() { return 1; } #ifdef __cplusplus }; // extern "C" #endif #define OMP_INIT_EX() #define OMP_LOOP_EX_BEGIN() #define OMP_LOOP_EX_END() #define OMP_THROW_EX() #endif #endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions FPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. The /// element type here is ExprWithCleanups::Object. SmallVector<BlockDecl*, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the FP_CONTRACT state on entry/exit of compound /// statements. class FPContractStateRAII { public: FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } private: Sema& S; FPOptions OldFPFeaturesState; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getFPOptions() { return FPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Expr *E); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return !D->isHidden() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T) { return !RequireCompleteTypeImpl(Loc, T, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as a non-type, and an expression representing /// that name has been formed. NC_ContextIndependentExpr, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification ContextIndependentExpr(ExprResult E) { NameClassification Result(NC_ContextIndependentExpr); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_ContextIndependentExpr); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); DeclContext *getContainingDC(DeclContext *DC); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Uuid); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true); ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfOnlyViableOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(E, nullptr, Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(ER, nullptr, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); // "({..})" // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, and false is returned. bool CheckConstraintExpression(Expr *CE); bool CalculateConstraintSatisfaction(ConceptDecl *NamedConcept, MultiLevelTemplateArgumentList &MLTAL, Expr *ConstraintExpr, bool &IsSatisfied); /// Check that the associated constraints of a template declaration match the /// associated constraints of an older declaration of which it is a /// redeclaration. bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old, TemplateParameterList *New); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(Decl *D); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); void CheckDelayedMemberExceptionSpecs(); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbigiousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, AccessSpecifier access, QualType objectType); void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, SourceLocation TemplateKWLoc = SourceLocation(), AssumedTemplateKind *ATK = nullptr); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnDependentTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); // Concepts Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression, UPPC_Block }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, TemplateDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); VarDecl *getVarTemplateSpecialization( VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispAttr::Mode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = Ext; } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. unsigned DeclareTargetNestingLevel = 0; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckForDelayedContext = true); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckCaller = true); /// Check if the expression is allowed to be used in expressions for the /// OpenMP devices. void checkOpenMPDeviceExpr(const Expr *E); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Marks all the functions that might be required for the currently active /// OpenMP context. void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse); public: /// Struct to store the context selectors info for declare variant directive. struct OpenMPDeclareVariantCtsSelectorData { OMPDeclareVariantAttr::CtxSelectorSetType CtxSet = OMPDeclareVariantAttr::CtxSetUnknown; OMPDeclareVariantAttr::CtxSelectorType Ctx = OMPDeclareVariantAttr::CtxUnknown; MutableArrayRef<StringRef> ImplVendors; ExprResult CtxScore; explicit OpenMPDeclareVariantCtsSelectorData() = default; explicit OpenMPDeclareVariantCtsSelectorData( OMPDeclareVariantAttr::CtxSelectorSetType CtxSet, OMPDeclareVariantAttr::CtxSelectorType Ctx, MutableArrayRef<StringRef> ImplVendors, ExprResult CtxScore) : CtxSet(CtxSet), Ctx(Ctx), ImplVendors(ImplVendors), CtxScore(CtxScore) {} }; /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); /// Called at the end of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, ArrayRef<OMPClause *> ClauseList); /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return DeclareTargetNestingLevel > 0; } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction( DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param Data Set of context-specific data for the specified context /// selector. void ActOnOpenMPDeclareVariantDirective( FunctionDecl *FD, Expr *VariantRef, SourceRange SR, const Sema::OpenMPDeclareVariantCtsSelectorData &Data); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, OpenMPLinearClauseKind LinKind, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation DepLinMapLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause *ActOnOpenMPFromClause( ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This is DefaultFunctionArrayLvalueConversion, // except that it assumes the operand isn't of function or array // type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign = false); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit, ImplicitConversionSequence& ICS); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion, bool &FunctionConversion); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); virtual ~VerifyICEDiagnoser() { } }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// A partial call graph maintained during CUDA/OpenMP device code compilation /// to support deferred diagnostics. /// /// Functions are only added here if, at the time they're considered, they are /// not known-emitted. As soon as we discover that a function is /// known-emitted, we remove it and everything it transitively calls from this /// set and add those functions to DeviceKnownEmittedFns. llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, SourceLocation>> DeviceCallGraph; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); DeviceDiagBuilder(DeviceDiagBuilder &&D); DeviceDiagBuilder(const DeviceDiagBuilder &) = default; ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Indicate that this function (and thus everything it transtively calls) /// will be codegen'ed, and emit any deferred diagnostics on this function and /// its (transitive) callees. void markKnownEmitted( Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, SourceLocation OrigLoc, const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas declared inside __device__ or __global__ functions inherit /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ /// functions become __host__ __device__ themselves. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteAfterIf(Scope *S); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; decltype(DelayedDllExportClasses) SavedDllExportClasses; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); SavedDllExportClasses.swap(S.DelayedDllExportClasses); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
main.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define N 2000 #define TIMES 20 int a[N][N], b[N][N]; int c[N][N]; int res[N][N]; int one_d[N * N]; int reduce[N][N]; int transpose_reduce[N][N]; int transpose_reduce_shared[N][N]; double eval_times[6][TIMES]; double cal_time(struct timespec *t_end, struct timespec *t_start) { double elapsedTime; elapsedTime = (t_end->tv_sec - t_start->tv_sec) * 1000.0; elapsedTime += (t_end->tv_nsec - t_start->tv_nsec) / 1000000.0; return elapsedTime; } int test(int time) { struct timespec t_start, t_end; int i, j, f, k; // Generate data for (i = 0; i < N; i++) for (j = 0; j < N; j++) { a[i][j] = rand() % 10; b[i][j] = rand() % 10; } // Sequential clock_gettime(CLOCK_REALTIME, &t_start); for (i = 0; i < N; i++) for (j = 0; j < N; j++) { c[i][j] = 0; for (k = 0; k < N; k++) c[i][j] += a[i][k] * b[k][j]; } clock_gettime(CLOCK_REALTIME, &t_end); double final_seq = cal_time(&t_end, &t_start); printf("Sequential time: %lf ms\n", final_seq); // Parallel clock_gettime(CLOCK_REALTIME, &t_start); #pragma omp parallel for collapse(2) shared(res, a, b) schedule(dynamic, 16) for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { res[i][j] = 0; for (int k = 0; k < N; k++) { res[i][j] += a[i][k] * b[k][j]; } } clock_gettime(CLOCK_REALTIME, &t_end); double final_par = cal_time(&t_end, &t_start); printf("Parallel time: %lf ms\n", final_par); // Reduce access times + Parallel clock_gettime(CLOCK_REALTIME, &t_start); #pragma omp parallel for collapse(2) shared(reduce, a, b) schedule(dynamic, 16) for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = 0; for (int k = 0; k < N; k++) { sum += a[i][k] * b[k][j]; } reduce[i][j] = sum; } } clock_gettime(CLOCK_REALTIME, &t_end); double final_reduce = cal_time(&t_end, &t_start); printf("Parallel reduce time: %lf ms\n", final_reduce); // Access 1D array + Reduce access times + Parallel clock_gettime(CLOCK_REALTIME, &t_start); #pragma omp parallel for collapse(2) shared(one_d, a, b) schedule(dynamic, 16) for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = 0; one_d[i * N + j] = 0; for (int k = 0; k < N; k++) { sum += a[i][k] * b[k][j]; } one_d[i * N + j] = sum; } } clock_gettime(CLOCK_REALTIME, &t_end); double final_1d = cal_time(&t_end, &t_start); printf("Parallel 1d time: %lf ms\n", final_1d); // Transpose + Reduce + parallel with no schedule clock_gettime(CLOCK_REALTIME, &t_start); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { int temp = b[i][j]; b[i][j] = b[j][i]; b[j][i] = temp; } } #pragma omp parallel for shared(transpose_reduce_shared, a, b) collapse(2) schedule(dynamic, 16) for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { transpose_reduce[i][j] = 0; for (int k = 0; k < N; k++) { transpose_reduce[i][j] += a[i][k] * b[j][k]; } } } clock_gettime(CLOCK_REALTIME, &t_end); double final_transpose_reduce = cal_time(&t_end, &t_start); printf("Parallel transpose_reduce time: %lf ms\n", final_transpose_reduce); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { int temp = b[i][j]; b[i][j] = b[j][i]; b[j][i] = temp; } } // Transpose + Reduce + parallel clock_gettime(CLOCK_REALTIME, &t_start); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { int temp = b[i][j]; b[i][j] = b[j][i]; b[j][i] = temp; } } #pragma omp parallel for shared(transpose_reduce_shared, a, b) collapse(2) schedule(dynamic, 16) for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = 0; transpose_reduce_shared[i][j] = 0; for (int k = 0; k < N; k++) { sum += a[i][k] * b[j][k]; } transpose_reduce_shared[i][j] = sum; } } clock_gettime(CLOCK_REALTIME, &t_end); double best = cal_time(&t_end, &t_start); printf("Parallel transpose_reduce_shared time: %lf ms\n", best); // Evaluation for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { if (c[i][j] != res[i][j] || c[i][j] != one_d[i * N + j] || c[i][j] != reduce[i][j] || c[i][j] != transpose_reduce[i][j] || c[i][j] != transpose_reduce_shared[i][j]) { break; } } } if (i == N && j == N) printf("Test pass!!!\n"); else { printf("Test failure..\n"); return 0; } eval_times[0][time] = final_seq; eval_times[1][time] = final_par; eval_times[2][time] = final_reduce; eval_times[3][time] = final_1d; eval_times[4][time] = final_transpose_reduce; eval_times[5][time] = best; } int main() { for (int i = 0; i < TIMES; i++) { test(i); } double avg; for (int i = 0; i < 6; i++) { avg = 0; for (int j = 0; j < TIMES; j++) { avg += eval_times[i][j]; } printf("Method %d: Avg=%lf\n", i, avg / TIMES); } return 0; }
array_transpose.h
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // 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 _H_ARRAY_TRANSPOSE #define _H_ARRAY_TRANSPOSE #include "secure_c_wrapper.h" #include "affinity_policy.h" template <int branch, typename T> static inline void inner_transpose_template(unsigned int tileSize, unsigned int *inputDims, const T *input, unsigned int *outputDims, T *output, unsigned int *transposeDims, int inputDimsNum, int outputDimsNum, unsigned int outputSize, int sizeInnerIndex) { #ifdef _USE_OPENMP #pragma omp parallel num_threads(OMP_NUM_THREADS) #endif { std::vector<unsigned int> inputLocalIndex(inputDimsNum); #ifdef _USE_OPENMP #pragma omp for #endif for (unsigned int i = 0; i < outputSize; i++) { unsigned int outputIndex = i; for (int j = sizeInnerIndex; j < outputDimsNum; j++) { unsigned int value = outputIndex % outputDims[j]; outputIndex /= outputDims[j]; inputLocalIndex[inputDimsNum - 1 - transposeDims[outputDimsNum - 1 - j]] = value; } unsigned int inputIndex = 0; for (int j = inputDimsNum - 1; j > sizeInnerIndex; j--) { inputIndex = (inputIndex + inputLocalIndex[j]) * inputDims[j - 1]; } inputIndex += inputLocalIndex[sizeInnerIndex]; if (branch == 0) { *(output + i) = *(input + inputIndex); } else { UNI_MEMCPY(output + i * tileSize, input + inputIndex * tileSize, tileSize); } } } } inline void array_transpose(unsigned int elementSize, unsigned int *inputDims, const void *input, unsigned int *outputDims, void *output, unsigned int *transposeDims, int inputDimsNum, int outputDimsNum) { unsigned int sizeInner = 1; int sizeInnerIndex = 0; for (int i = outputDimsNum - 1; i >= 0; i--) { if ((int)transposeDims[i] == i) { sizeInner *= inputDims[inputDimsNum - 1 - i]; sizeInnerIndex++; } else { break; } } int tileSize = elementSize * sizeInner; int in = inputDims[inputDimsNum - 1], ihiw = 0, ic = 0; if (outputDimsNum - sizeInnerIndex == 3 && transposeDims[0] == 0 && transposeDims[1] == 2 && transposeDims[2] == 1) { ic = inputDims[inputDimsNum - 2]; ihiw = inputDims[inputDimsNum - 3]; } if (outputDimsNum - sizeInnerIndex == 4 && transposeDims[0] == 0 && transposeDims[1] == 2 && transposeDims[2] == 3 && transposeDims[3] == 1) { ic = inputDims[inputDimsNum - 2]; ihiw = inputDims[inputDimsNum - 3] * inputDims[inputDimsNum - 4]; } if (ic > 0 && ihiw > 0 && input != output) { #ifdef _USE_OPENMP #pragma omp parallel for num_threads(OMP_NUM_THREADS) #endif for (int o = 0; o < in * ihiw; o++) { int n = o / ihiw; int hw = o % ihiw; U8 *dst = (U8 *)output + o * ic * tileSize; for (int c = 0; c < ic; c++, dst += tileSize) { const U8 *src = (const U8 *)input + ((n * ic + c) * ihiw + hw) * tileSize; UNI_MEMCPY(dst, src, tileSize); } } return; } unsigned int inputSize = 1, outputSize = 1; for (int i = 0; i < inputDimsNum; i++) { inputSize *= inputDims[i]; } for (int i = 0; i < outputDimsNum; i++) { outputSize *= outputDims[i]; } CHECK_REQUIREMENT(inputSize == outputSize); outputSize = outputSize / sizeInner; const char *inputPtr = (const char *)input; char *outputPtr = (char *)output; if (sizeInner == 1 && elementSize == 4) { inner_transpose_template<0, int>(elementSize, inputDims, (const int *)input, outputDims, (int *)output, transposeDims, inputDimsNum, outputDimsNum, outputSize, sizeInnerIndex); } else if (sizeInner == 1 && elementSize == 2) { inner_transpose_template<0, short>(elementSize, inputDims, (const short *)input, outputDims, (short *)output, transposeDims, inputDimsNum, outputDimsNum, outputSize, sizeInnerIndex); } else { inner_transpose_template<1, char>(tileSize, inputDims, (const char *)input, outputDims, (char *)output, transposeDims, inputDimsNum, outputDimsNum, outputSize, sizeInnerIndex); } } inline void array_transpose_naive(unsigned int elementSize, unsigned int *inputDims, const void *input, unsigned int *outputDims, void *output, unsigned int *transposeDims, int dimsNum) { if (dimsNum <= 1) { return; } unsigned int inputSize = 1, outputSize = 1; for (int i = 0; i < dimsNum; i++) { inputSize *= inputDims[i]; outputSize *= outputDims[i]; } const char *inputPtr = (const char *)input; char *outputPtr = (char *)output; #ifdef _USE_OPENMP #pragma omp parallel num_threads(OMP_NUM_THREADS) #endif { std::vector<unsigned int> inputLocalIndex(dimsNum); #ifdef _USE_OPENMP #pragma omp for #endif for (unsigned int i = 0; i < outputSize; i++) { unsigned int outputIndex = i; for (int j = 0; j < dimsNum; j++) { unsigned int value = outputIndex % outputDims[j]; outputIndex /= outputDims[j]; inputLocalIndex[dimsNum - 1 - transposeDims[dimsNum - 1 - j]] = value; } unsigned int inputIndex = 0; for (int j = dimsNum - 1; j > 0; j--) { inputIndex = (inputIndex + inputLocalIndex[j]) * inputDims[j - 1]; } inputIndex += inputLocalIndex[0]; UNI_MEMCPY( outputPtr + i * elementSize, inputPtr + inputIndex * elementSize, elementSize); } } } #endif
normalmap.c
#include <assert.h> #include <math.h> // sqrtf #include <stdlib.h> // malloc, free #include <string.h> // memset #include "normalmap.h" #include <stdio.h> // DEBUG typedef struct { int xOffset; int yOffset; float weight; } KernelElement; typedef struct { KernelElement * elements; int elementCount; } Kernel; const char * NormalMapFilterToString( NormalMapFilter filter ) { switch(filter) { case Prewitt3x3: return "Prewitt3x3"; case Prewitt5x5: return "Prewitt5x5"; case Sobel3x3: return "Sobel3x3"; case Sobel5x5: return "Sobel5x5"; case Scharr3x3: return "Scharr3x3"; case Scharr5x5: return "Scharr5x5"; case NormalMapFilterCount: ; // fallthrough } assert(!"Unknown normal map filter."); return NULL; } static float * CreateRotatedKernelWeights( int size, const float * source ) { float * destination = (float *)malloc(sizeof(float)*size*size); for(int y = 0; y < size; y++) for(int x = 0; x < size; x++) { destination[x*size + y] = source[y*size + x]; } return destination; } static Kernel * CreateKernel( int size, const float * weights ) { int elementCount = 0; for(int i = 0; i < size*size; i++) if(weights[i] != 0) elementCount++; assert(elementCount > 0); KernelElement * elements = (KernelElement *)malloc(sizeof(KernelElement)*elementCount); int elementIndex = 0; for(int i = 0; i < size*size; i++) { if(weights[i] != 0) { const int x = i % size; const int y = (i-x) / size; KernelElement * element = &elements[elementIndex]; element->xOffset = x - (size / 2); element->yOffset = y - (size / 2); element->weight = weights[i]; elementIndex++; } } assert(elementIndex == elementCount); Kernel * kernel = (Kernel *)malloc(sizeof(Kernel)); kernel->elements = elements; kernel->elementCount = elementCount; return kernel; } static void FreeKernel( Kernel * kernel ) { assert(kernel->elements != NULL); free(kernel->elements); memset(kernel, 0, sizeof(Kernel)); free(kernel); } static const float Prewitt3x3XWeights[] = { -1, 0, +1, -1, 0, +1, -1, 0, +1 }; static const float Prewitt5x5XWeights[] = { -2, -1, 0, +1, +2, -2, -1, 0, +1, +2, -2, -1, 0, +1, +2, -2, -1, 0, +1, +2, -2, -1, 0, +1, +2 }; static const float Sobel3x3XWeights[] = { -1, 0, +1, -2, 0, +2, -1, 0, +1 }; static const float Sobel5x5XWeights[] = { -1, -2, 0, +2, +1, -4, -8, 0, +8, +4, -6, -12, 0, +12, +6, -4, -8, 0, +8, +4, -1, -2, 0, +2, +1 }; static const float Scharr3x3XWeights[] = { -3, 0, +3, -10, 0, +10, -3, 0, +3 }; static const float Scharr5x5XWeights[] = { -1, -1, 0, +1, +1, -2, -2, 0, +2, +2, -3, -6, 0, +6, +3, -2, -2, 0, +2, +2, -1, -1, 0, +1, +1 }; static void CreateXandYKernels( int size, const float * xWeights, Kernel * * xKernel, Kernel * * yKernel ) { float * yWeights = CreateRotatedKernelWeights(size, xWeights); *xKernel = CreateKernel(size, xWeights); *yKernel = CreateKernel(size, yWeights); free(yWeights); } static void CreateFilterKernels( NormalMapFilter filter, Kernel * * xKernel, Kernel * * yKernel ) { switch(filter) { case Prewitt3x3: CreateXandYKernels(3, Prewitt3x3XWeights, xKernel, yKernel); return; case Prewitt5x5: CreateXandYKernels(5, Prewitt5x5XWeights, xKernel, yKernel); return; case Sobel3x3: CreateXandYKernels(3, Sobel3x3XWeights, xKernel, yKernel); return; case Sobel5x5: CreateXandYKernels(5, Sobel5x5XWeights, xKernel, yKernel); return; case Scharr3x3: CreateXandYKernels(3, Scharr3x3XWeights, xKernel, yKernel); return; case Scharr5x5: CreateXandYKernels(5, Scharr5x5XWeights, xKernel, yKernel); return; case NormalMapFilterCount: // fallthrough ; } assert(!"Unknown normal map filter."); } static int GetCroppedMapIndex( int width, int height, int x, int y ) { if(x < 0) x = 0; else if(x >= width) x = width-1; if(y < 0) y = 0; else if(y >= height) y = height-1; return y*width + x; } static int GetWrappedMapIndex( int width, int height, int x, int y ) { if(x < 0) x = x+width; else if(x >= width) x = x-width; if(y < 0) y = y+height; else if(y >= height) y = y-height; return y*width + x; } static float ApplyKernel( const Kernel * kernel, const float * map, int width, int height, bool wrap, int x, int y ) { float result = 0; for(int i = 0; i < kernel->elementCount; i++) { const KernelElement * kernelElement = &kernel->elements[i]; int mapIndex; if(wrap) mapIndex = GetWrappedMapIndex(width, height, x + kernelElement->xOffset, y + kernelElement->yOffset); else mapIndex = GetCroppedMapIndex(width, height, x + kernelElement->xOffset, y + kernelElement->yOffset); assert(mapIndex >= 0 && mapIndex < width*height); result += map[mapIndex] * kernelElement->weight; } return -result; // TODO: Must be inverted because otherwise the normalmap doesn't looks right. But why? } static void Normalize( float * v ) { const float length = sqrtf(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); if(length > 1e-04f) { const float invLength = 1.0f / length; v[0] *= invLength; v[1] *= invLength; v[2] *= invLength; } else { v[0] = 0; v[1] = 0; v[2] = 0; } } static void NormalToRGB( float * v ) { v[0] = v[0]*0.5f + 0.5f; v[1] = v[1]*0.5f + 0.5f; v[2] = v[2]*0.5f + 0.5f; assert(v[0] >= 0 && v[0] <= 1 && v[1] >= 0 && v[1] <= 1 && v[2] >= 0 && v[2] <= 1); } void GenerateNormalMap( int width, int height, const float * heightMap, float * normalMap, NormalMapFilter filter, bool wrap, bool invertY ) { Kernel * xKernel; Kernel * yKernel; CreateFilterKernels(filter, &xKernel, &yKernel); const float yModifier = invertY ? 1 : -1; // Flip Y by default, to be compatible with normal maps generated by Blender. #pragma omp parallel for collapse(2) for(int y = 0; y < height; y++) for(int x = 0; x < width; x++) { float * normal = &normalMap[(y*width + x)*3]; normal[0] = ApplyKernel(xKernel, heightMap, width, height, wrap, x, y); normal[1] = ApplyKernel(yKernel, heightMap, width, height, wrap, x, y); normal[1] *= yModifier; normal[2] = 1.0f; Normalize(normal); NormalToRGB(normal); } FreeKernel(xKernel); FreeKernel(yKernel); }
gramschmidt.c
/** * gramschmidt.c: This file was adapted from PolyBench/GPU 1.0 test * suite to run on GPU with OpenMP 4.0 pragmas and OpenCL driver. * * http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU * * Contacts: Marcio M Pereira <mpereira@ic.unicamp.br> * Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br> * Luís Felipe Mattos <ra107822@students.ic.unicamp.br> */ #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #ifdef _OPENMP #include <omp.h> #endif #include "BenchmarksUtil.h" // define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 0.05 /* Problem size. */ #ifdef RUN_TEST #define SIZE 1100 #elif RUN_BENCHMARK #define SIZE 9600 #else #define SIZE 1000 #endif /* Problem size */ #define M SIZE #define N SIZE /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void gramschmidt(DATA_TYPE *A, DATA_TYPE *R, DATA_TYPE *Q) { int i, j, k; DATA_TYPE nrm; for (k = 0; k < N; k++) { nrm = 0; for (i = 0; i < M; i++) { nrm += A[i * N + k] * A[i * N + k]; } R[k * N + k] = sqrt(nrm); for (i = 0; i < M; i++) { Q[i * N + k] = A[i * N + k] / R[k * N + k]; } for (j = k + 1; j < N; j++) { R[k * N + j] = 0; for (i = 0; i < M; i++) { R[k * N + j] += Q[i * N + k] * A[i * N + j]; } for (i = 0; i < M; i++) { A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j]; } } } } void gramschmidt_OMP(DATA_TYPE *A, DATA_TYPE *R, DATA_TYPE *Q) { int i, j, k; DATA_TYPE nrm; #pragma omp target data map(to: R[:M*N], Q[:M*N]) map(tofrom: A[:M*N]) device(DEVICE_ID) { for (k = 0; k < N; k++) { // CPU nrm = 0; #pragma omp target update from(A[:M*N]) for (i = 0; i < M; i++) { nrm += A[i * N + k] * A[i * N + k]; } R[k * N + k] = sqrt(nrm); for (i = 0; i < M; i++) { Q[i * N + k] = A[i * N + k] / R[k * N + k]; } #pragma omp target update to(Q[:M*N]) #pragma omp target teams distribute parallel for private(i) for (j = k + 1; j < N; j++) { R[k * N + j] = 0; for (i = 0; i < M; i++) { R[k * N + j] += Q[i * N + k] * A[i * N + j]; } for (i = 0; i < M; i++) { A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j]; } } } } } void init_array(DATA_TYPE *A, DATA_TYPE *A2) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { A[i * N + j] = ((DATA_TYPE)(i + 1) * (j + 1)) / (M + 1); A2[i * N + j] = A[i * N + j]; } } } int compareResults(DATA_TYPE *A, DATA_TYPE *A_outputFromGpu) { int i, j, fail; fail = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { if (percentDiff(A[i * N + j], A_outputFromGpu[i * N + j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; // printf("i: %d j: %d \n1: %f\n 2: %f\n", i, j, A[i*N + j], // A_outputFromGpu[i*N + j]); } } } // Print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f " "Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail); return fail; } int main(int argc, char *argv[]) { double t_start, t_end; int fail = 0; DATA_TYPE *A; DATA_TYPE *A_outputFromGpu; DATA_TYPE *R; DATA_TYPE *Q; A = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); A_outputFromGpu = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); R = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); Q = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE)); fprintf(stdout, "<< Gram-Schmidt decomposition >>\n"); init_array(A, A_outputFromGpu); t_start = rtclock(); gramschmidt_OMP(A_outputFromGpu, R, Q); t_end = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start); #ifdef RUN_TEST t_start = rtclock(); gramschmidt(A, R, Q); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); fail = compareResults(A, A_outputFromGpu); #endif free(A); free(A_outputFromGpu); free(R); free(Q); return fail; }
monotonic-1.c
/* { dg-do run } */ #ifndef MONOTONIC_TYPE #include <omp.h> #include <stdlib.h> #define MONOTONIC_TYPE int #define MONOTONIC_UNDEF -1 #define MONOTONIC_END(n) n #endif int main () { MONOTONIC_TYPE i; #pragma omp parallel { int cnt = omp_get_num_threads (); int thr = omp_get_thread_num (); MONOTONIC_TYPE l = MONOTONIC_UNDEF; int c = 0; int n = 0; #pragma omp for nowait schedule(static, 5) for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else { if (l >= i) abort (); if (cnt == 1) abort (); if (n != 5) abort (); n = 1; c++; } if (n == 1) { if ((i % 5) != 0) abort (); if ((i / 5) % cnt != thr) abort (); } l = i; } if (cnt == 1) { if (n != 73 || l != 73 - 1 || c != 1) abort (); } else if (thr > 73 / 5) { if (l != MONOTONIC_UNDEF || c != 0 || n != 0) abort (); } else if (thr == 73 / 5) { if (l != 73 - 1 || c != 1 || n != 73 % 5) abort (); } else if (c == 0) abort (); else if (l == 73 - 1) { if (thr != (73 / 5) % cnt || n != 73 % 5) abort (); } else if ((n % 5) != 0) abort (); l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for schedule( monotonic: static, 7) nowait for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else { if (l >= i) abort (); if (cnt == 1) abort (); if (n != 7) abort (); n = 1; c++; } if (n == 1) { if ((i % 7) != 0) abort (); if ((i / 7) % cnt != thr) abort (); } l = i; } if (cnt == 1) { if (n != 73 || l != 73 - 1 || c != 1) abort (); } else if (thr > 73 / 7) { if (l != MONOTONIC_UNDEF || c != 0 || n != 0) abort (); } else if (thr == 73 / 7) { if (l != 73 - 1 || c != 1 || n != 73 % 7) abort (); } else if (c == 0) abort (); else if (l == 73 - 1) { if (thr != (73 / 7) % cnt || n != 73 % 7) abort (); } else if ((n % 7) != 0) abort (); l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for nowait schedule(static) for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else abort (); l = i; } if (c > 1) abort (); l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for nowait schedule(monotonic,simd:static) for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else abort (); l = i; } if (c > 1) abort (); l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for schedule(monotonic : dynamic, 5) nowait for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else { if (l >= i) abort (); if ((n % 5) != 0 || n == 0) abort (); n = 1; c++; } l = i; } if (l == 73 - 1) { if (n % 5 != 73 % 5) abort (); } else if (l == MONOTONIC_UNDEF) { if (n != 0 || c != 0) abort (); } else if ((n % 5) != 0 || n == 0) abort (); l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for nowait schedule(dynamic, 7) ordered(1) for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else { if (l >= i) abort (); if ((n % 7) != 0 || n == 0) abort (); n = 1; c++; } #pragma omp ordered depend(source) if (MONOTONIC_UNDEF > 0) { #pragma omp ordered depend(sink: i) } else { #pragma omp ordered depend(sink: i - 1) } l = i; } if (l == 73 - 1) { if (n % 7 != 73 % 7) abort (); } else if (l == MONOTONIC_UNDEF) { if (n != 0 || c != 0) abort (); } else if ((n % 7) != 0 || n == 0) abort (); l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for schedule (monotonic :guided , 7) nowait for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else { if (l >= i) abort (); if (n < 7) abort (); n = 1; c++; } l = i; } l = MONOTONIC_UNDEF; c = 0; n = 0; #pragma omp for nowait schedule(guided, 7) ordered for (i = 0; i < MONOTONIC_END (73); i++) { if (l == MONOTONIC_UNDEF) { n = 1; c++; } else if (l == i - 1) n++; else { if (l >= i) abort (); if (n < 7) abort (); n = 1; c++; } #pragma omp ordered l = i; } } return 0; }
irbuilder_unroll_partial_heuristic_constant_for.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=51 -x c -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics // REQUIRES: x86-registered-target // TODO: The unroll-factor heuristic might be able to use the information that the trip count is constant, but currently is not able to determine that. #ifndef HEADER #define HEADER double sind(double); // CHECK-LABEL: define {{.*}}@unroll_partial_heuristic_constant_for( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[E_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[OFFSET_ADDR:.+]] = alloca float, align 4 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8 // CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8 // CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8 // CHECK-NEXT: store float* %[[E:.+]], float** %[[E_ADDR]], align 8 // CHECK-NEXT: store float %[[OFFSET:.+]], float* %[[OFFSET_ADDR]], align 4 // CHECK-NEXT: store i32 0, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: %[[TMP3:.+]] = udiv i32 %[[DOTCOUNT]], 4 // CHECK-NEXT: %[[TMP4:.+]] = urem i32 %[[DOTCOUNT]], 4 // CHECK-NEXT: %[[TMP5:.+]] = icmp ne i32 %[[TMP4]], 0 // CHECK-NEXT: %[[TMP6:.+]] = zext i1 %[[TMP5]] to i32 // CHECK-NEXT: %[[OMP_FLOOR0_TRIPCOUNT:.+]] = add nuw i32 %[[TMP3]], %[[TMP6]] // CHECK-NEXT: br label %[[OMP_FLOOR0_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_PREHEADER]]: // CHECK-NEXT: store i32 0, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = sub i32 %[[OMP_FLOOR0_TRIPCOUNT]], 1 // CHECK-NEXT: store i32 %[[TMP7]], i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4 // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 34, i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]], i32 1, i32 0) // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: %[[TMP10:.+]] = sub i32 %[[TMP9]], %[[TMP8]] // CHECK-NEXT: %[[TMP11:.+]] = add i32 %[[TMP10]], 1 // CHECK-NEXT: br label %[[OMP_FLOOR0_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_HEADER]]: // CHECK-NEXT: %[[OMP_FLOOR0_IV:.+]] = phi i32 [ 0, %[[OMP_FLOOR0_PREHEADER]] ], [ %[[OMP_FLOOR0_NEXT:.+]], %[[OMP_FLOOR0_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_FLOOR0_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_COND]]: // CHECK-NEXT: %[[OMP_FLOOR0_CMP:.+]] = icmp ult i32 %[[OMP_FLOOR0_IV]], %[[TMP11]] // CHECK-NEXT: br i1 %[[OMP_FLOOR0_CMP]], label %[[OMP_FLOOR0_BODY:.+]], label %[[OMP_FLOOR0_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_BODY]]: // CHECK-NEXT: %[[TMP12:.+]] = add i32 %[[OMP_FLOOR0_IV]], %[[TMP8]] // CHECK-NEXT: %[[TMP13:.+]] = icmp eq i32 %[[TMP12]], %[[OMP_FLOOR0_TRIPCOUNT]] // CHECK-NEXT: %[[TMP14:.+]] = select i1 %[[TMP13]], i32 %[[TMP4]], i32 4 // CHECK-NEXT: br label %[[OMP_TILE0_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_PREHEADER]]: // CHECK-NEXT: br label %[[OMP_TILE0_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_HEADER]]: // CHECK-NEXT: %[[OMP_TILE0_IV:.+]] = phi i32 [ 0, %[[OMP_TILE0_PREHEADER]] ], [ %[[OMP_TILE0_NEXT:.+]], %[[OMP_TILE0_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_TILE0_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_COND]]: // CHECK-NEXT: %[[OMP_TILE0_CMP:.+]] = icmp ult i32 %[[OMP_TILE0_IV]], %[[TMP14]] // CHECK-NEXT: br i1 %[[OMP_TILE0_CMP]], label %[[OMP_TILE0_BODY:.+]], label %[[OMP_TILE0_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_BODY]]: // CHECK-NEXT: %[[TMP15:.+]] = mul nuw i32 4, %[[TMP12]] // CHECK-NEXT: %[[TMP16:.+]] = add nuw i32 %[[TMP15]], %[[OMP_TILE0_IV]] // CHECK-NEXT: br label %[[OMP_LOOP_BODY:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[TMP16]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP17:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP18:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = sext i32 %[[TMP18]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP17]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP19:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[CONV:.+]] = fpext float %[[TMP19]] to double // CHECK-NEXT: %[[CALL:.+]] = call double @sind(double noundef %[[CONV]]) // CHECK-NEXT: %[[TMP20:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP21:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM2:.+]] = sext i32 %[[TMP21]] to i64 // CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP20]], i64 %[[IDXPROM2]] // CHECK-NEXT: %[[TMP22:.+]] = load float, float* %[[ARRAYIDX3]], align 4 // CHECK-NEXT: %[[CONV4:.+]] = fpext float %[[TMP22]] to double // CHECK-NEXT: %[[MUL:.+]] = fmul double %[[CALL]], %[[CONV4]] // CHECK-NEXT: %[[TMP23:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP24:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM5:.+]] = sext i32 %[[TMP24]] to i64 // CHECK-NEXT: %[[ARRAYIDX6:.+]] = getelementptr inbounds float, float* %[[TMP23]], i64 %[[IDXPROM5]] // CHECK-NEXT: %[[TMP25:.+]] = load float, float* %[[ARRAYIDX6]], align 4 // CHECK-NEXT: %[[CONV7:.+]] = fpext float %[[TMP25]] to double // CHECK-NEXT: %[[MUL8:.+]] = fmul double %[[MUL]], %[[CONV7]] // CHECK-NEXT: %[[TMP26:.+]] = load float*, float** %[[E_ADDR]], align 8 // CHECK-NEXT: %[[TMP27:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM9:.+]] = sext i32 %[[TMP27]] to i64 // CHECK-NEXT: %[[ARRAYIDX10:.+]] = getelementptr inbounds float, float* %[[TMP26]], i64 %[[IDXPROM9]] // CHECK-NEXT: %[[TMP28:.+]] = load float, float* %[[ARRAYIDX10]], align 4 // CHECK-NEXT: %[[CONV11:.+]] = fpext float %[[TMP28]] to double // CHECK-NEXT: %[[MUL12:.+]] = fmul double %[[MUL8]], %[[CONV11]] // CHECK-NEXT: %[[TMP29:.+]] = load float, float* %[[OFFSET_ADDR]], align 4 // CHECK-NEXT: %[[CONV13:.+]] = fpext float %[[TMP29]] to double // CHECK-NEXT: %[[ADD:.+]] = fadd double %[[MUL12]], %[[CONV13]] // CHECK-NEXT: %[[TMP30:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP31:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM14:.+]] = sext i32 %[[TMP31]] to i64 // CHECK-NEXT: %[[ARRAYIDX15:.+]] = getelementptr inbounds float, float* %[[TMP30]], i64 %[[IDXPROM14]] // CHECK-NEXT: %[[TMP32:.+]] = load float, float* %[[ARRAYIDX15]], align 4 // CHECK-NEXT: %[[CONV16:.+]] = fpext float %[[TMP32]] to double // CHECK-NEXT: %[[ADD17:.+]] = fadd double %[[CONV16]], %[[ADD]] // CHECK-NEXT: %[[CONV18:.+]] = fptrunc double %[[ADD17]] to float // CHECK-NEXT: store float %[[CONV18]], float* %[[ARRAYIDX15]], align 4 // CHECK-NEXT: br label %[[OMP_TILE0_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_INC]]: // CHECK-NEXT: %[[OMP_TILE0_NEXT]] = add nuw i32 %[[OMP_TILE0_IV]], 1 // CHECK-NEXT: br label %[[OMP_TILE0_HEADER]], !llvm.loop ![[LOOP3:[0-9]+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_EXIT]]: // CHECK-NEXT: br label %[[OMP_TILE0_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_AFTER]]: // CHECK-NEXT: br label %[[OMP_FLOOR0_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_INC]]: // CHECK-NEXT: %[[OMP_FLOOR0_NEXT]] = add nuw i32 %[[OMP_FLOOR0_IV]], 1 // CHECK-NEXT: br label %[[OMP_FLOOR0_HEADER]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_EXIT]]: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]]) // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM19:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM19]]) // CHECK-NEXT: br label %[[OMP_FLOOR0_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_AFTER]]: // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } void unroll_partial_heuristic_constant_for(float *a, float *b, float *c, float *d, float *e, float offset) { #pragma omp for #pragma omp unroll partial for (int i = 0; i < 128; i++) { a[i] += sind(b[i]) * c[i] * d[i] * e[i] + offset; } } #endif // HEADER // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: store i32 128, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 1, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp slt i32 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub nsw i32 %[[TMP6]], %[[TMP7]] // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP8]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]] // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP9]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 1, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 51} // CHECK: ![[META2:[0-9]+]] = // CHECK: ![[LOOP3]] = distinct !{![[LOOP3]], ![[LOOPPROP4:[0-9]+]], ![[LOOPPROP5:[0-9]+]]} // CHECK: ![[LOOPPROP4]] = !{!"llvm.loop.unroll.enable"} // CHECK: ![[LOOPPROP5]] = !{!"llvm.loop.unroll.count", i32 4}
integrator.h
#ifndef _INTEGRATOR_H #define _INTEGRATOR_H #include <omp.h> #include <optional> #include "camera.h" #include "core.h" #include "image.h" #include "photon_map.h" #include "scene.h" class Integrator { protected: const std::shared_ptr<Camera> camera; public: Integrator(const std::shared_ptr<Camera>& camera) : camera(camera) {} // render scene virtual void render(const Scene& scene, Sampler& sampler, Image& image) = 0; // compute cosine term // NOTE: need to account for the asymmetry of BSDF when photon tracing // https://pbr-book.org/3ed-2018/Light_Transport_III_Bidirectional_Methods/The_Path-Space_Measurement_Equation#x3-Non-symmetryDuetoShadingNormals // Veach, Eric. Robust Monte Carlo methods for light transport simulation. // Stanford University, 1998. Section 5.3 static float cosTerm(const Vec3f& wo, const Vec3f& wi, const SurfaceInfo& surfaceInfo, const TransportDirection& transport_dir) { const float wi_ns = dot(wi, surfaceInfo.shadingNormal); const float wi_ng = dot(wi, surfaceInfo.geometricNormal); const float wo_ns = dot(wo, surfaceInfo.shadingNormal); const float wo_ng = dot(wo, surfaceInfo.geometricNormal); // prevent light leaks if (wi_ng * wi_ns <= 0 || wo_ng * wo_ns <= 0) { return 0; } if (transport_dir == TransportDirection::FROM_CAMERA) { return std::abs(wi_ns); } else if (transport_dir == TransportDirection::FROM_LIGHT) { return std::abs(wo_ns) * std::abs(wi_ng) / std::abs(wo_ng); } else { spdlog::error("[Integrator] invalid transport direction"); std::exit(EXIT_FAILURE); } } }; // abstraction of path based integrator class PathIntegrator : public Integrator { private: // number of samples in each pixel const uint32_t n_samples; public: // compute radiance coming from the given ray virtual Vec3f integrate(const Ray& ray, const Scene& scene, Sampler& sampler) const = 0; PathIntegrator(const std::shared_ptr<Camera>& camera, uint32_t n_samples) : Integrator(camera), n_samples(n_samples) {} void render(const Scene& scene, Sampler& sampler, Image& image) override final { const uint32_t width = image.getWidth(); const uint32_t height = image.getHeight(); spdlog::info("[PathIntegrator] rendering..."); #pragma omp parallel for collapse(2) schedule(dynamic, 1) for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { // init sampler for each pixel const std::unique_ptr<Sampler> sampler_per_pixel = sampler.clone(); sampler_per_pixel->setSeed((sampler.getSeed() + 1) * (j + width * i)); // warmup sampler for (uint32_t k = 0; k < 100; ++k) { sampler_per_pixel->getNext1D(); } // iteration for (uint32_t k = 0; k < n_samples; ++k) { // SSAA const float u = (2.0f * (j + sampler_per_pixel->getNext1D()) - width) / height; const float v = (2.0f * (i + sampler_per_pixel->getNext1D()) - height) / height; Ray ray; float pdf; if (camera->sampleRay(Vec2f(u, v), *sampler_per_pixel, ray, pdf)) { // compute incoming radiance const Vec3f radiance = integrate(ray, scene, *sampler_per_pixel) / pdf; // invalid radiance check if (std::isnan(radiance[0]) || std::isnan(radiance[1]) || std::isnan(radiance[2])) { spdlog::error("[PathIntegrator] radiance is NaN"); continue; } else if (std::isinf(radiance[0]) || std::isinf(radiance[1]) || std::isinf(radiance[2])) { spdlog::error("[PathIntegrator] radiance is inf"); continue; } else if (radiance[0] < 0 || radiance[1] < 0 || radiance[2] < 0) { spdlog::error("[PathIntegrator] radiance is minus"); continue; } image.addPixel(i, j, radiance); } else { image.setPixel(i, j, Vec3f(0)); } } } } spdlog::info("[PathIntegrator] done"); // take average image /= Vec3f(n_samples); } }; // implementation of path tracing // NOTE: for reference purpose class PathTracing : public PathIntegrator { private: const uint32_t maxDepth; public: PathTracing(const std::shared_ptr<Camera>& camera, uint32_t n_samples, uint32_t maxDepth = 100) : PathIntegrator(camera, n_samples), maxDepth(maxDepth) {} Vec3f integrate(const Ray& ray_in, const Scene& scene, Sampler& sampler) const override { Vec3f radiance(0); Ray ray = ray_in; Vec3f throughput(1, 1, 1); for (uint32_t k = 0; k < maxDepth; ++k) { IntersectInfo info; if (scene.intersect(ray, info)) { // russian roulette if (k > 0) { const float russian_roulette_prob = std::min( std::max(throughput[0], std::max(throughput[1], throughput[2])), 1.0f); if (sampler.getNext1D() >= russian_roulette_prob) { break; } throughput /= russian_roulette_prob; } // Le if (info.hitPrimitive->hasAreaLight()) { radiance += throughput * info.hitPrimitive->Le(info.surfaceInfo, -ray.direction); } // sample direction by BxDF Vec3f dir; float pdf_dir; Vec3f f = info.hitPrimitive->sampleBxDF( -ray.direction, info.surfaceInfo, TransportDirection::FROM_CAMERA, sampler, dir, pdf_dir); // update throughput and ray throughput *= f * cosTerm(-ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_CAMERA) / pdf_dir; ray = Ray(info.surfaceInfo.position, dir); } else { break; } } return radiance; } }; // this implementation is based on modified version of original SPPM // Knaus, Claude, and Matthias Zwicker. // "Progressive photon mapping: A probabilistic approach." ACM Transactions on // Graphics (TOG) 30.3 (2011): 1-13. class PPMAPA : public Integrator { private: // number of iterations const uint32_t nIterations; // number of photons in each iteration const uint32_t nPhotons; // parameter for radius reduction, see the paper const float alpha; // maximum tracing depth const uint32_t maxDepth; // number of emitted photons uint32_t nEmittedPhotons; // global search radius for radiance estimation float globalRadius; PhotonMap photonMap; // compute reflected radiance with photon map Vec3f computeRadianceWithPhotonMap(const Vec3f& wo, const IntersectInfo& info) const { // get nearby photons const std::vector<int> photon_indices = photonMap.queryPhotonsInRange(info.surfaceInfo.position, globalRadius); Vec3f Lo; for (const int photon_idx : photon_indices) { const Photon& photon = photonMap.getIthPhoton(photon_idx); const Vec3f f = info.hitPrimitive->evaluateBxDF( wo, photon.wi, info.surfaceInfo, TransportDirection::FROM_CAMERA); Lo += f * photon.throughput; } Lo /= (nPhotons * PI * globalRadius * globalRadius); return Lo; } // sample initial ray from light and compute initial throughput Ray sampleRayFromLight(const Scene& scene, Sampler& sampler, Vec3f& throughput) { // sample light float light_choose_pdf; const std::shared_ptr<Light> light = scene.sampleLight(sampler, light_choose_pdf); // sample point on light float light_pos_pdf; const SurfaceInfo light_surf = light->samplePoint(sampler, light_pos_pdf); // sample direction on light float light_dir_pdf; const Vec3f dir = light->sampleDirection(light_surf, sampler, light_dir_pdf); // spawn ray Ray ray(light_surf.position, dir); throughput = light->Le(light_surf, dir) / (light_choose_pdf * light_pos_pdf * light_dir_pdf) * std::abs(dot(dir, light_surf.shadingNormal)); return ray; } // photon tracing and build photon map void buildPhotonMap(const Scene& scene, std::vector<std::unique_ptr<Sampler>>& samplers) { // photon tracing std::vector<Photon> photons; // spdlog::info("[PPMAPA] tracing photons..."); #pragma omp parallel for for (uint32_t i = 0; i < nPhotons; ++i) { auto& sampler_per_thread = *samplers[omp_get_thread_num()]; // sample initial ray from light and set initial throughput Vec3f throughput; Ray ray = sampleRayFromLight(scene, sampler_per_thread, throughput); // trace photons // whener hitting diffuse surface, add photon to the photon array // recursively tracing photon with russian roulette for (uint32_t k = 0; k < maxDepth; ++k) { if (std::isnan(throughput[0]) || std::isnan(throughput[1]) || std::isnan(throughput[2])) { spdlog::error("[PPMAPA] photon throughput is NaN"); break; } else if (throughput[0] < 0 || throughput[1] < 0 || throughput[2] < 0) { spdlog::error("[PPMAPA] photon throughput is minus"); break; } IntersectInfo info; if (scene.intersect(ray, info)) { const BxDFType bxdf_type = info.hitPrimitive->getBxDFType(); if (bxdf_type == BxDFType::DIFFUSE) { // TODO: remove lock to get more speed #pragma omp critical { photons.emplace_back(throughput, info.surfaceInfo.position, -ray.direction); } } // russian roulette if (k > 0) { const float russian_roulette_prob = std::min( std::max(throughput[0], std::max(throughput[1], throughput[2])), 1.0f); if (sampler_per_thread.getNext1D() >= russian_roulette_prob) { break; } throughput /= russian_roulette_prob; } // sample direction by BxDF Vec3f dir; float pdf_dir; const Vec3f f = info.hitPrimitive->sampleBxDF( -ray.direction, info.surfaceInfo, TransportDirection::FROM_LIGHT, sampler_per_thread, dir, pdf_dir); // update throughput and ray throughput *= f * cosTerm(-ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_LIGHT) / pdf_dir; ray = Ray(info.surfaceInfo.position, dir); } else { // photon goes to the sky break; } } } // spdlog::info("[PPMAPA] done"); // build photon map // spdlog::info("[PPMAPA] building photon map..."); photonMap.setPhotons(photons); photonMap.build(); // spdlog::info("[PPMAPA] done"); } // compute incoming radiance with photon map Vec3f integrate(const Ray& ray_in, const Scene& scene, Sampler& sampler) const { Ray ray = ray_in; Vec3f throughput(1, 1, 1); for (uint32_t k = 0; k < maxDepth; ++k) { IntersectInfo info; if (scene.intersect(ray, info)) { // when directly hitting light if (info.hitPrimitive->hasAreaLight()) { return throughput * info.hitPrimitive->Le(info.surfaceInfo, -ray.direction); } const BxDFType bxdf_type = info.hitPrimitive->getBxDFType(); // if hitting diffuse surface, compute reflected radiance with photon // map if (bxdf_type == BxDFType::DIFFUSE) { return throughput * computeRadianceWithPhotonMap(-ray.direction, info); } // if hitting specular surface, generate next ray and continue tracing else if (bxdf_type == BxDFType::SPECULAR) { // sample direction by BxDF Vec3f dir; float pdf_dir; Vec3f f = info.hitPrimitive->sampleBxDF( -ray.direction, info.surfaceInfo, TransportDirection::FROM_CAMERA, sampler, dir, pdf_dir); // update throughput and ray throughput *= f * cosTerm(-ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_CAMERA) / pdf_dir; ray = Ray(info.surfaceInfo.position, dir); } } else { // ray goes out the the sky break; } } return Vec3f(0); } public: PPMAPA(const std::shared_ptr<Camera>& camera, uint32_t nIterations, uint32_t nPhotons, float alpha, float initialRadius, uint32_t maxDepth = 100) : Integrator(camera), nIterations(nIterations), nPhotons(nPhotons), alpha(alpha), globalRadius(initialRadius), maxDepth(maxDepth), nEmittedPhotons(0) {} void render(const Scene& scene, Sampler& sampler, Image& image) override { // init sampler for each thread std::vector<std::unique_ptr<Sampler>> samplers(omp_get_max_threads()); for (int i = 0; i < samplers.size(); ++i) { samplers[i] = sampler.clone(); samplers[i]->setSeed(sampler.getSeed() * (i + 1)); // warpup sampler for (int j = 0; j < 10; ++j) { samplers[i]->getNext1D(); } } const uint32_t width = image.getWidth(); const uint32_t height = image.getHeight(); spdlog::info("[PPMAPA] rendering..."); for (uint32_t iteration = 0; iteration < nIterations; ++iteration) { spdlog::info("[PPMAPA] iteration: {}", iteration); spdlog::info("[PPMAPA] radius: {}", globalRadius); // clear previous photon map photonMap.clear(); // photon tracing and build photon map // spdlog::info("[PPMAPA] photon tracing pass..."); buildPhotonMap(scene, samplers); nEmittedPhotons += nPhotons; // spdlog::info("[PPMAPA] done"); // eye tracing // spdlog::info("[PPMAPA] eye tracing pass..."); #pragma omp parallel for collapse(2) schedule(dynamic, 1) for (uint32_t i = 0; i < height; ++i) { for (uint32_t j = 0; j < width; ++j) { auto& sampler_per_thread = *samplers[omp_get_thread_num()]; // SSAA const float u = (2.0f * (j + sampler_per_thread.getNext1D()) - width) / height; const float v = (2.0f * (i + sampler_per_thread.getNext1D()) - height) / height; Ray ray; float pdf; if (camera->sampleRay(Vec2f(u, v), sampler_per_thread, ray, pdf)) { // compute incoming radiance with photon map const Vec3f radiance = integrate(ray, scene, sampler_per_thread) / pdf; // invalid radiance check if (std::isnan(radiance[0]) || std::isnan(radiance[1]) || std::isnan(radiance[2])) { spdlog::error("[SPPM] radiance is NaN"); continue; } else if (std::isinf(radiance[0]) || std::isinf(radiance[1]) || std::isinf(radiance[2])) { spdlog::error("[SPPM] radiance is inf"); continue; } else if (radiance[0] < 0 || radiance[1] < 0 || radiance[2] < 0) { spdlog::error("[SPPM] radiance is minus"); continue; } // add contribution image.addPixel(i, j, radiance); } else { image.setPixel(i, j, Vec3f(0)); } } } // spdlog::info("[SPPM] done"); // update search radius globalRadius = std::sqrt((iteration + alpha) / (iteration + 1)) * globalRadius; // save image at each iteration // Image image_copied = image; // image_copied /= Vec3f(iteration + 1); // image_copied.gammaCorrection(2.2f); // image_copied.writePPM("iteration_" + std::to_string(iteration) + // ".ppm"); } // take average image /= Vec3f(nIterations); spdlog::info("[PPMAPA] done"); } }; #endif
lsh_index.h
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * 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 AUTHOR ``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 AUTHOR 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: Vincent Rabaud *************************************************************************/ #ifndef FLANN_LSH_INDEX_H_ #define FLANN_LSH_INDEX_H_ #include <algorithm> #include <cassert> #include <cstring> #include <map> #include <vector> #include "flann/general.h" #include "flann/algorithms/nn_index.h" #include "flann/util/matrix.h" #include "flann/util/result_set.h" #include "flann/util/heap.h" #include "flann/util/lsh_table.h" #include "flann/util/allocator.h" #include "flann/util/random.h" #include "flann/util/saving.h" namespace flann { struct LshIndexParams : public IndexParams { LshIndexParams(unsigned int table_number = 12, unsigned int key_size = 20, unsigned int multi_probe_level = 2) { (* this)["algorithm"] = FLANN_INDEX_LSH; // The number of hash tables to use (*this)["table_number"] = table_number; // The length of the key in the hash tables (*this)["key_size"] = key_size; // Number of levels to use in multi-probe (0 for standard LSH) (*this)["multi_probe_level"] = multi_probe_level; } }; /** * Randomized kd-tree index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. */ template<typename Distance> class LshIndex : public NNIndex<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; typedef Eigen::Matrix<ElementType, Eigen::Dynamic, Eigen::Dynamic> MatrixType; typedef Eigen::Matrix<ElementType, Eigen::Dynamic, 1> VectorType; typedef Eigen::Matrix<DistanceType, Eigen::Dynamic, Eigen::Dynamic> DistanceMatrix; typedef Eigen::Matrix<DistanceType, Eigen::Dynamic, 1> DistanceVector; typedef Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic> IndexMatrix; typedef Eigen::Matrix<size_t, Eigen::Dynamic, 1> IndexVector; typedef NNIndex<Distance> BaseClass; /** Constructor * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const IndexParams& params = LshIndexParams(), Distance d = Distance()) : BaseClass(params, d) { table_number_ = get_param<unsigned int>(index_params_,"table_number",12); key_size_ = get_param<unsigned int>(index_params_,"key_size",20); multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2); fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); } /** Constructor * @param input_data dataset with the input features * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const Matrix<ElementType>& input_data, const IndexParams& params = LshIndexParams(), Distance d = Distance()) : BaseClass(params, d) { table_number_ = get_param<unsigned int>(index_params_,"table_number",12); key_size_ = get_param<unsigned int>(index_params_,"key_size",20); multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2); fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); setDataset(input_data); } LshIndex(const LshIndex& other) : BaseClass(other), tables_(other.tables_), table_number_(other.table_number_), key_size_(other.key_size_), multi_probe_level_(other.multi_probe_level_), xor_masks_(other.xor_masks_) { } LshIndex& operator=(LshIndex other) { this->swap(other); return *this; } virtual ~LshIndex() { freeIndex(); } BaseClass* clone() const { return new LshIndex(*this); } using BaseClass::buildIndex; void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2) { assert(points.cols==veclen_); size_t old_size = size_; extendDataset(points); if (rebuild_threshold>1 && size_at_build_*rebuild_threshold<size_) { buildIndex(); } else { for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable<ElementType>& table = tables_[i]; for (size_t i=old_size;i<size_;++i) { table.add(i, points_[i]); } } } } flann_algorithm_t getType() const { return FLANN_INDEX_LSH; } template<typename Archive> void serialize(Archive& ar) { ar.setObject(this); ar & *static_cast<NNIndex<Distance>*>(this); ar & table_number_; ar & key_size_; ar & multi_probe_level_; ar & xor_masks_; ar & tables_; if (Archive::is_loading::value) { index_params_["algorithm"] = getType(); index_params_["table_number"] = table_number_; index_params_["key_size"] = key_size_; index_params_["multi_probe_level"] = multi_probe_level_; } } void saveIndex(FILE* stream) { serialization::SaveArchive sa(stream); sa & *this; } void loadIndex(FILE* stream) { serialization::LoadArchive la(stream); la & *this; } /** * Computes the index memory usage * Returns: memory used by the index */ int usedMemory() const { return size_ * sizeof(int); } /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ int knnSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen_); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(indices.cols >= knn); assert(dists.cols >= knn); int count = 0; if (params.use_heap==FLANN_True) { #pragma omp parallel num_threads(params.cores) { KNNUniqueResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } return count; } /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ int knnSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen_); if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); int count = 0; if (params.use_heap==FLANN_True) { #pragma omp parallel num_threads(params.cores) { KNNUniqueResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } return count; } /** * Find set of nearest neighbors to vec. Their indices are stored inside * the result object. * * Params: * result = the result object in which the indices of the nearest-neighbors are stored * vec = the vector for which to search the nearest neighbors * maxCheck = the maximum number of restarts (in a best-bin-first manner) */ void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& /*searchParams*/) const { getNeighbors(vec, result); } protected: /** * Builds the index */ void buildIndexImpl() { tables_.resize(table_number_); std::vector<std::pair<size_t,ElementType*> > features; features.reserve(points_.size()); for (size_t i=0;i<points_.size();++i) { features.push_back(std::make_pair(i, points_[i])); } for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable<ElementType>& table = tables_[i]; table = lsh::LshTable<ElementType>(veclen_, key_size_); // Add the features to the table table.add(features); } } void freeIndex() { /* nothing to do here */ } private: /** Defines the comparator on score and index */ typedef std::pair<float, unsigned int> ScoreIndexPair; struct SortScoreIndexPairOnSecond { bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const { return left.second < right.second; } }; /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH * @param key the key we build neighbors from * @param lowest_index the lowest index of the bit set * @param level the multi-probe level we are at * @param xor_masks all the xor mask */ void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, std::vector<lsh::BucketKey>& xor_masks) { xor_masks.push_back(key); if (level == 0) return; for (int index = lowest_index - 1; index >= 0; --index) { // Create a new key lsh::BucketKey new_key = key | (lsh::BucketKey(1) << index); fill_xor_mask(new_key, index, level - 1, xor_masks); } } /** Performs the approximate nearest-neighbor search. * @param vec the feature to analyze * @param do_radius flag indicating if we check the radius too * @param radius the radius if it is a radius search * @param do_k flag indicating if we limit the number of nn * @param k_nn the number of nearest neighbors * @param checked_average used for debugging */ void getNeighbors(const ElementType* vec, bool do_radius, float radius, bool do_k, unsigned int k_nn, float& checked_average) { static std::vector<ScoreIndexPair> score_index_heap; if (do_k) { unsigned int worst_score = std::numeric_limits<unsigned int>::max(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; hamming_distance = distance_(vec, points_[*training_index].point, veclen_); if (hamming_distance < worst_score) { // Insert the new element score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); std::push_heap(score_index_heap.begin(), score_index_heap.end()); if (score_index_heap.size() > (unsigned int)k_nn) { // Remove the highest distance value as we have too many elements std::pop_heap(score_index_heap.begin(), score_index_heap.end()); score_index_heap.pop_back(); // Keep track of the worst score worst_score = score_index_heap.front().first; } } } } } } else { typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; // Compute the Hamming distance hamming_distance = distance_(vec, points_[*training_index].point, veclen_); if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); } } } } } /** Performs the approximate nearest-neighbor search. * This is a slower version than the above as it uses the ResultSet * @param vec the feature to analyze */ void getNeighbors(const ElementType* vec, ResultSet<DistanceType>& result) const { typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; // Compute the Hamming distance hamming_distance = distance_(vec, points_[*training_index], veclen_); result.addPoint(hamming_distance, *training_index); } } } } void swap(LshIndex& other) { BaseClass::swap(other); std::swap(tables_, other.tables_); std::swap(size_at_build_, other.size_at_build_); std::swap(table_number_, other.table_number_); std::swap(key_size_, other.key_size_); std::swap(multi_probe_level_, other.multi_probe_level_); std::swap(xor_masks_, other.xor_masks_); } /** The different hash tables */ std::vector<lsh::LshTable<ElementType> > tables_; /** table number */ unsigned int table_number_; /** key size */ unsigned int key_size_; /** How far should we look for neighbors in multi-probe LSH */ unsigned int multi_probe_level_; /** The XOR masks to apply to a key to get the neighboring buckets */ std::vector<lsh::BucketKey> xor_masks_; USING_BASECLASS_SYMBOLS }; } #endif //FLANN_LSH_INDEX_H_
tool_available.c
// The OpenMP standard defines 3 ways of providing ompt_start_tool: // 1. "statically-linking the tool’s definition of ompt_start_tool into an // OpenMP application" // RUN: %libomp-compile -DCODE -DTOOL && env OMP_TOOL_VERBOSE_INIT=stdout \ // RUN: %libomp-run | FileCheck %s --check-prefixes CHECK,ADDRSPACE // Note: We should compile the tool without -fopenmp as other tools developer // would do. Otherwise this test may pass for the wrong reasons on Darwin. // RUN: %clang %flags -DTOOL -shared -fPIC %s -o %T/tool.so // 2. "introducing a dynamically-linked library that includes the tool’s // definition of ompt_start_tool into the application’s address space" // 2.1 Link with tool during compilation // RUN: %libomp-compile -DCODE %no-as-needed-flag %T/tool.so && \ // RUN: env OMP_TOOL_VERBOSE_INIT=stdout %libomp-run | FileCheck %s \ // RUN: --check-prefixes CHECK,ADDRSPACE // 2.2 Link with tool during compilation, but AFTER the runtime // RUN: %libomp-compile -DCODE -lomp %no-as-needed-flag %T/tool.so && \ // RUN: env OMP_TOOL_VERBOSE_INIT=stdout %libomp-run | FileCheck %s \ // RUN: --check-prefixes CHECK,ADDRSPACE // 2.3 Inject tool via the dynamic loader // RUN: %libomp-compile -DCODE && env OMP_TOOL_VERBOSE_INIT=stdout \ // RUN: %preload-tool %libomp-run | FileCheck %s \ // RUN: --check-prefixes CHECK,ADDRSPACE // 3. "providing the name of a dynamically-linked library appropriate for the // architecture and operating system used by the application in the // tool-libraries-var ICV" // 3.1 OMP_TOOL_VERBOSE_INIT not set // RUN: %libomp-compile -DCODE && \ // RUN: env OMP_TOOL_LIBRARIES=%T/tool.so %libomp-run | FileCheck %s // 3.2 OMP_TOOL_VERBOSE_INIT disabled // RUN: env OMP_TOOL_LIBRARIES=%T/tool.so OMP_TOOL_VERBOSE_INIT=disabled \ // RUN: %libomp-run | FileCheck %s // 3.3 OMP_TOOL_VERBOSE_INIT to stdout // RUN: %libomp-compile -DCODE && env OMP_TOOL_LIBRARIES=%T/tool.so \ // RUN: OMP_TOOL_VERBOSE_INIT=stdout %libomp-run | \ // RUN: FileCheck %s -DPARENTPATH=%T --check-prefixes CHECK,TOOLLIB // 3.4 OMP_TOOL_VERBOSE_INIT to stderr, check merged stdout and stderr // RUN: env OMP_TOOL_LIBRARIES=%T/tool.so OMP_TOOL_VERBOSE_INIT=stderr \ // RUN: %libomp-run 2>&1 | \ // RUN: FileCheck %s -DPARENTPATH=%T --check-prefixes CHECK,TOOLLIB // 3.5 OMP_TOOL_VERBOSE_INIT to stderr, check just stderr // RUN: env OMP_TOOL_LIBRARIES=%T/tool.so OMP_TOOL_VERBOSE_INIT=stderr \ // RUN: %libomp-run 2>&1 >/dev/null | \ // RUN: FileCheck %s -DPARENTPATH=%T --check-prefixes TOOLLIB // 3.6 OMP_TOOL_VERBOSE_INIT to file "init.log" // RUN: env OMP_TOOL_LIBRARIES=%T/tool.so OMP_TOOL_VERBOSE_INIT=%T/init.log \ // RUN: %libomp-run | FileCheck %s && cat %T/init.log | \ // RUN: FileCheck %s -DPARENTPATH=%T --check-prefixes TOOLLIB // REQUIRES: ompt /* * This file contains code for an OMPT shared library tool to be * loaded and the code for the OpenMP executable. * -DTOOL enables the code for the tool during compilation * -DCODE enables the code for the executable during compilation */ // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback // ADDRSPACE: ----- START LOGGING OF TOOL REGISTRATION ----- // ADDRSPACE-NEXT: Search for OMP tool in current address space... Sucess. // ADDRSPACE-NEXT: Tool was started and is using the OMPT interface. // ADDRSPACE-NEXT: ----- END LOGGING OF TOOL REGISTRATION ----- // TOOLLIB: ----- START LOGGING OF TOOL REGISTRATION ----- // TOOLLIB-NEXT: Search for OMP tool in current address space... Failed. // TOOLLIB-NEXT: Searching tool libraries... // TOOLLIB-NEXT: OMP_TOOL_LIBRARIES = [[PARENTPATH]]/tool.so // TOOLLIB-NEXT: Opening [[PARENTPATH]]/tool.so... Success. // TOOLLIB-NEXT: Searching for ompt_start_tool in // TOOLLIB-SAME: [[PARENTPATH]]/tool.so... Success. // TOOLLIB-NEXT: Tool was started and is using the OMPT interface. // TOOLLIB-NEXT: ----- END LOGGING OF TOOL REGISTRATION ----- #ifdef CODE #include "omp.h" int main() { #pragma omp parallel num_threads(2) { } // CHECK-NOT: ----- START LOGGING OF TOOL REGISTRATION ----- // CHECK-NOT: ----- END LOGGING OF TOOL REGISTRATION ----- // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}0: ompt_event_runtime_shutdown return 0; } #endif /* CODE */ #ifdef TOOL #include <stdio.h> #include <omp-tools.h> int ompt_initialize(ompt_function_lookup_t lookup, int initial_device_num, ompt_data_t *tool_data) { printf("0: NULL_POINTER=%p\n", (void*)NULL); return 1; //success } void ompt_finalize(ompt_data_t* tool_data) { printf("0: ompt_event_runtime_shutdown\n"); } ompt_start_tool_result_t* ompt_start_tool( unsigned int omp_version, const char *runtime_version) { static ompt_start_tool_result_t ompt_start_tool_result = {&ompt_initialize,&ompt_finalize, 0}; return &ompt_start_tool_result; } #endif /* TOOL */
tentusscher_epi_2004_S1_1.c
#include <assert.h> #include <stdlib.h> #include "tentusscher_epi_2004_S1_1.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.7787928226268,0.00123339508649700,0.784831144233936,0.784673023102172,0.000169405106163081,0.487281523786458,0.00289654265697758,0.999998418745548,1.86681673058670e-08,1.83872100639159e-05,0.999777546403090,1.00731261455043,0.999997755681027,4.00467125306598e-05,0.953040239833913,9.39175391367938,139.965667493392}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.7730247891532,0.000208550376791424,0.000166345602997405,0.000314427207496467,0.272150547490643,0.206045798160674,0.134878222351137,2.91860118931279,0.0222099400341836,2.12194476134155,1099.53480175178,0.000604923870766662,0.118384383617544,0.0193733747777405,0.00390066599158743,2.21704721596155e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
datatypes.h
#ifndef DATATYPES_H_ #define DATATYPES_H_ #include <stdbool.h> #include "../tools.h" #include "PlyDict.h" #include "ObjDict.h" #define MSG_HEAD_SEP "YGG_MSG_HEAD" /*! @brief Size of COMM buffer. */ #define COMMBUFFSIZ 2000 #define FMT_LEN 100 #ifdef __cplusplus /* If this is a C++ compiler, use C linkage */ extern "C" { #endif static char prefix_char = '#'; #ifdef _OPENMP #pragma omp threadprivate(prefix_char) #endif /*! @brief C-friendly definition of MetaschemaType. */ typedef struct dtype_t { char type[COMMBUFFSIZ]; //!< Type name bool use_generic; //!< Flag for empty dtypes to specify generic in/out void *obj; //!< MetaschemaType Pointer } dtype_t; /*! @brief C-friendly defintion of YggGeneric. */ typedef struct generic_t { char prefix; //!< Prefix character for limited verification. void *obj; //!< Pointer to YggGeneric class. } generic_t; /*! @brief C-friendly definition of vector object. */ typedef generic_t json_array_t; /*! @brief C-friendly definition of map object. */ typedef generic_t json_object_t; /*! @brief C-friendly definition of schema object. */ typedef generic_t schema_t; /*! @brief C-friendly defintion of Python class object. */ typedef python_t python_class_t; /*! @brief C-friendly defintion of Python function object. */ typedef python_t python_function_t; /*! @brief C-friendly defintion of Python instance object. */ typedef generic_t python_instance_t; /*! @brief Macro wrapping call to PyObject_CallFunction. */ #define call_python(x, format, ...) PyObject_CallFunction(x.obj, format, __VA_ARGS__) /*! @brief Aliases to allow differentiation in parsing model definition. */ typedef char* unicode_t; typedef char* string_t; typedef char* bytes_t; /*! @brief Header information passed by comms for multipart messages. */ typedef struct comm_head_t { int multipart; //!< 1 if message is multipart, 0 if it is not. size_t bodysiz; //!< Size of body. size_t bodybeg; //!< Start of body in header. int valid; //!< 1 if the header is valid, 0 otherwise. int nargs_populated; //!< Number of arguments populated during deserialization. // size_t size; //!< Size of incoming message. char address[COMMBUFFSIZ]; //!< Address that message will comm in on. char id[COMMBUFFSIZ]; //!< Unique ID associated with this message. char response_address[COMMBUFFSIZ]; //!< Response address. char request_id[COMMBUFFSIZ]; //!< Request id. char zmq_reply[COMMBUFFSIZ]; //!< Reply address for ZMQ sockets. char zmq_reply_worker[COMMBUFFSIZ]; //!< Reply address for worker socket. char model[COMMBUFFSIZ]; //!< Name of model that sent the header. int type_in_data; //!< 1 if type is stored with the data during serialization. // These should be removed once JSON fully implemented int serializer_type; //!< Code indicating the type of serializer. char format_str[COMMBUFFSIZ]; //!< Format string for serializer. char field_names[COMMBUFFSIZ]; //!< String containing field names. char field_units[COMMBUFFSIZ]; //!< String containing field units. int as_array; //!< 1 if messages will be serialized arrays. // dtype_t* dtype; //!< Type structure. } comm_head_t; /*! @brief C wrapper for the C++ type_from_doc function. @param type_doc void* Pointer to const rapidjson::Value type doc. @returns void* Pointer to MetaschemaType class. */ void* type_from_doc_c(const void* type_doc, const bool use_generic); /*! @brief C wrapper for the C++ type_from_pyobj function. @param type_doc void* Pointer to const rapidjson::Value type doc. @returns void* Pointer to MetaschemaType class. */ void* type_from_pyobj_c(PyObject* pyobj, const bool use_generic); /*! @brief Determine if a datatype was created from a format. @params[in] type_struct dtype_t* Datatype structure. @returns int 1 if the datatype was created from a format, 0 if it was not, -1 if there is an error. */ int is_dtype_format_array(dtype_t* type_struct); /*! @brief Initialize an empty generic object. @returns generic_t New generic object structure. */ generic_t init_generic(); /*! @brief Initialize an empty array of mixed types with generic wrappers. @returns generic_t New generic object structure containing an empty array. */ generic_t init_generic_array(); /*! @brief Initialize an empty map (JSON object) of mixed types with generic wrappers. @returns generic_t New generic object structure contaiing an empty map (JSON object). */ generic_t init_generic_map(); /*! @brief Determine if the provided character matches the required generic prefix char. @param[in] x char Character to check. @returns int 1 if the character is the correct prefix, 0 otherwise. */ int is_generic_flag(char x); /*! @brief Determine if a generic structure is initialized. @param[in] x generic_t Generic structure to test. @returns int 1 if the structure is initialized, 0 otherwise. */ int is_generic_init(generic_t x); /*! @brief Create a generic object from the provided information. @param[in] type_class dtype_t* Type structure/class. @param[in] data void* Pointer to data. @param[in] nbytes size_t Size of data. @returns generic_t Pointer to new generic object structure. */ generic_t create_generic(dtype_t* type_class, void* data, size_t nbytes); /*! @brief Destroy a generic object. @param[in] x generic_t* Pointer to generic object structure to destory. @returns int -1 if unsuccessful, 0 otherwise. */ int destroy_generic(generic_t* x); /*! @brief Copy data from one generic object to the other. @param[in] src generic_t Generic structure that data should be copied from. @returns generic_t Copied structure. */ generic_t copy_generic(generic_t src); /*! @brief Display information about the generic type. @param[in] x generic_t* Wrapper for generic object. */ void display_generic(generic_t x); /*! @brief Return the recovered generic structure if one is present in the variable argument list. @param[in] nargs size_t Number of argument present in ap. @param[in] ap va_list_t Variable argument list. @returns generic_t Generic structure if one is present. */ generic_t get_generic_va(size_t nargs, va_list_t ap); /*! @brief Return the recovered generic structure if one is present in the variable argument list. @param[in] nargs size_t Number of argument present in ap. @param[in] ap va_list_t Variable argument list. @returns generic_t* Generic structure if one is present, NULL otherwise. */ generic_t* get_generic_va_ptr(size_t nargs, va_list_t ap); /*! @brief Return the recovered generic structure if one is present in the variable argument list by removing it. @param[in] nargs size_t* Pointer to number of arguments present in ap that will be decremented by 1. @param[in] ap va_list_t* Pointer to variable argument list. @returns generic_t Generic structure if one is present. */ generic_t pop_generic_va(size_t* nargs, va_list_t* ap); /*! @brief Return the recovered generic structure if one is present in the variable argument list by removing it. @param[in] nargs size_t* Pointer to number of arguments present in ap that will be decremented by 1. @param[in] ap va_list_t* Pointer to variable argument list. @returns generic_t* Generic structure if one is present, NULL otherwise. */ generic_t* pop_generic_va_ptr(size_t* nargs, va_list_t* ap); /*! @brief Add an element to the end of an array of generic elements. @param[in] arr generic_t Array to add element to. @param[in] x generic_t Element to add. @returns int Flag that is 1 if there is an error and 0 otherwise. */ int add_generic_array(generic_t arr, generic_t x); /*! @brief Set an element in the array at a given index to a new value. @param[in] arr generic_t Array to add element to. @param[in] i size_t Index where element should be added. @param[in] x generic_t Element to add. @returns int Flag that is 1 if there is an error and 0 otherwise. */ int set_generic_array(generic_t arr, size_t i, generic_t x); /*! @brief Get an element from an array. @param[in] arr generic_t Array to get element from. @param[in] i size_t Index of element to get. @param[out] x generic_t* Pointer to address where element should be stored. @returns int Flag that is 1 if there is an error and 0 otherwise. */ int get_generic_array(generic_t arr, size_t i, generic_t *x); /*! @brief Set an element in the object at for a given key to a new value. @param[in] arr generic_t Object to add element to. @param[in] k const char* Key where element should be added. @param[in] x generic_t Element to add. @returns int Flag that is 1 if there is an error and 0 otherwise. */ int set_generic_object(generic_t arr, const char* k, generic_t x); /*! @brief Get an element from an object. @param[in] arr generic_t Object to get element from. @param[in] k const char* Key of element to return. @param[out] x generic_t* Pointer to address where element should be stored. @returns int Flag that is 1 if there is an error and 0 otherwise. */ int get_generic_object(generic_t arr, const char* k, generic_t *x); /*! @brief Get the number of elements in an array object. @param[in] x generic_t Generic object that is presumed to contain an array. @returns size_t Number of elements in array. */ size_t generic_array_get_size(generic_t x); /*! @brief Get an item from an array for types that don't require additional parameters. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be returned. @param[in] type const char* Type of value expected. @returns void* Pointer to data for array item. */ void* generic_array_get_item(generic_t x, const size_t index, const char *type); int generic_array_get_item_nbytes(generic_t x, const size_t index); bool generic_array_get_bool(generic_t x, const size_t index); int generic_array_get_integer(generic_t x, const size_t index); void* generic_array_get_null(generic_t x, const size_t index); double generic_array_get_number(generic_t x, const size_t index); char* generic_array_get_string(generic_t x, const size_t index); generic_t generic_array_get_object(generic_t x, const size_t index); generic_t generic_array_get_array(generic_t x, const size_t index); char* generic_array_get_direct(generic_t x, const size_t index); ply_t generic_array_get_ply(generic_t x, const size_t index); obj_t generic_array_get_obj(generic_t x, const size_t index); python_t generic_array_get_python_class(generic_t x, const size_t index); python_t generic_array_get_python_function(generic_t x, const size_t index); schema_t generic_array_get_schema(generic_t x, const size_t index); generic_t generic_array_get_any(generic_t x, const size_t index); /*! @brief Get a scalar value from an array. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be returned. @param[in] subtype const char* Subtype of scalar expected. @param[in] precision const int Precision of scalar that is expected. @returns void* Pointer to scalar data. */ void* generic_array_get_scalar(generic_t x, const size_t index, const char *subtype, const size_t precision); int8_t generic_array_get_int8(generic_t x, const size_t index); int16_t generic_array_get_int16(generic_t x, const size_t index); int32_t generic_array_get_int32(generic_t x, const size_t index); int64_t generic_array_get_int64(generic_t x, const size_t index); uint8_t generic_array_get_uint8(generic_t x, const size_t index); uint16_t generic_array_get_uint16(generic_t x, const size_t index); uint32_t generic_array_get_uint32(generic_t x, const size_t index); uint64_t generic_array_get_uint64(generic_t x, const size_t index); float generic_array_get_float(generic_t x, const size_t index); double generic_array_get_double(generic_t x, const size_t index); long double generic_array_get_long_double(generic_t x, const size_t index); complex_float_t generic_array_get_complex_float(generic_t x, const size_t index); complex_double_t generic_array_get_complex_double(generic_t x, const size_t index); complex_long_double_t generic_array_get_complex_long_double(generic_t x, const size_t index); char* generic_array_get_bytes(generic_t x, const size_t index); char* generic_array_get_unicode(generic_t x, const size_t index); /*! @brief Get a 1d array value from an array. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be returned. @param[in] subtype const char* Subtype of array expected. @param[in] precision const size_t Precision of array that is expected. @param[out] data void** Pointer to pointer that should be reallocated to store the data. @returns size_t Number of elements in the data. */ size_t generic_array_get_1darray(generic_t x, const size_t index, const char *subtype, const size_t precision, void** data); size_t generic_array_get_1darray_int8(generic_t x, const size_t index, int8_t** data); size_t generic_array_get_1darray_int16(generic_t x, const size_t index, int16_t** data); size_t generic_array_get_1darray_int32(generic_t x, const size_t index, int32_t** data); size_t generic_array_get_1darray_int64(generic_t x, const size_t index, int64_t** data); size_t generic_array_get_1darray_uint8(generic_t x, const size_t index, uint8_t** data); size_t generic_array_get_1darray_uint16(generic_t x, const size_t index, uint16_t** data); size_t generic_array_get_1darray_uint32(generic_t x, const size_t index, uint32_t** data); size_t generic_array_get_1darray_uint64(generic_t x, const size_t index, uint64_t** data); size_t generic_array_get_1darray_float(generic_t x, const size_t index, float** data); size_t generic_array_get_1darray_double(generic_t x, const size_t index, double** data); size_t generic_array_get_1darray_long_double(generic_t x, const size_t index, long double** data); size_t generic_array_get_1darray_complex_float(generic_t x, const size_t index, complex_float_t** data); size_t generic_array_get_1darray_complex_double(generic_t x, const size_t index, complex_double_t** data); size_t generic_array_get_1darray_complex_long_double(generic_t x, const size_t index, complex_long_double_t** data); size_t generic_array_get_1darray_bytes(generic_t x, const size_t index, char** data); size_t generic_array_get_1darray_unicode(generic_t x, const size_t index, char** data); /*! @brief Get a nd array value from an array. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be returned. @param[in] subtype const char* Subtype of array expected. @param[in] precision const size_t Precision of array that is expected. @param[out] data void** Pointer to array that should be reallocated to store the data. @param[out] shape size_t** Pointer to array that should be reallocated to store the array shape in each dimension. @returns size_t Number of dimensions in the array. */ size_t generic_array_get_ndarray(generic_t x, const size_t index, const char *subtype, const size_t precision, void** data, size_t** shape); size_t generic_array_get_ndarray_int8(generic_t x, const size_t index, int8_t** data, size_t** shape); size_t generic_array_get_ndarray_int16(generic_t x, const size_t index, int16_t** data, size_t** shape); size_t generic_array_get_ndarray_int32(generic_t x, const size_t index, int32_t** data, size_t** shape); size_t generic_array_get_ndarray_int64(generic_t x, const size_t index, int64_t** data, size_t** shape); size_t generic_array_get_ndarray_uint8(generic_t x, const size_t index, uint8_t** data, size_t** shape); size_t generic_array_get_ndarray_uint16(generic_t x, const size_t index, uint16_t** data, size_t** shape); size_t generic_array_get_ndarray_uint32(generic_t x, const size_t index, uint32_t** data, size_t** shape); size_t generic_array_get_ndarray_uint64(generic_t x, const size_t index, uint64_t** data, size_t** shape); size_t generic_array_get_ndarray_float(generic_t x, const size_t index, float** data, size_t** shape); size_t generic_array_get_ndarray_double(generic_t x, const size_t index, double** data, size_t** shape); size_t generic_array_get_ndarray_long_double(generic_t x, const size_t index, long double** data, size_t** shape); size_t generic_array_get_ndarray_complex_float(generic_t x, const size_t index, complex_float_t** data, size_t** shape); size_t generic_array_get_ndarray_complex_double(generic_t x, const size_t index, complex_double_t** data, size_t** shape); size_t generic_array_get_ndarray_complex_long_double(generic_t x, const size_t index, complex_long_double_t** data, size_t** shape); size_t generic_array_get_ndarray_bytes(generic_t x, const size_t index, char** data, size_t** shape); size_t generic_array_get_ndarray_unicode(generic_t x, const size_t index, char** data, size_t** shape); /*! @brief Get the number of elements in an map object. @param[in] x generic_t Generic object that is presumed to contain a map. @returns size_t Number of elements in map. */ size_t generic_map_get_size(generic_t x); /*! @brief Determine if a map object has a certain key. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key char* Key to check for. @returns int 1 if the key is present, 0 otherwise. */ int generic_map_has_key(generic_t x, char* key); /*! @brief Get the keys in a map object. @param[in] x generic_t Generic object that is presumed to contain a map. @param[out] keys char*** Pointer to memory where array of keys should be stored. @returns size_t Number of keys in map. */ size_t generic_map_get_keys(generic_t x, char*** keys); /*! @brief Get an item from a map for types that don't require additional parameters. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be returned. @param[in] type const char* Type of value expected. @returns void* Pointer to data for map item. */ void* generic_map_get_item(generic_t x, const char* key, const char *type); int generic_map_get_item_nbytes(generic_t x, const char* key); bool generic_map_get_bool(generic_t x, const char* key); int generic_map_get_integer(generic_t x, const char* key); void* generic_map_get_null(generic_t x, const char* key); double generic_map_get_number(generic_t x, const char* key); char* generic_map_get_string(generic_t x, const char* key); generic_t generic_map_get_object(generic_t x, const char* key); generic_t generic_map_get_array(generic_t x, const char* key); char* generic_map_get_direct(generic_t x, const char* key); ply_t generic_map_get_ply(generic_t x, const char* key); obj_t generic_map_get_obj(generic_t x, const char* key); python_t generic_map_get_python_class(generic_t x, const char* key); python_t generic_map_get_python_function(generic_t x, const char* key); schema_t generic_map_get_schema(generic_t x, const char* key); generic_t generic_map_get_any(generic_t x, const char* key); /*! @brief Get a scalar value from a map. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be returned. @param[in] subtype const char* Subtype of scalar expected. @param[in] precision const int Precision of scalar that is expected. @returns void* Pointer to scalar data. */ void* generic_map_get_scalar(generic_t x, const char* key, const char *subtype, const size_t precision); int8_t generic_map_get_int8(generic_t x, const char* key); int16_t generic_map_get_int16(generic_t x, const char* key); int32_t generic_map_get_int32(generic_t x, const char* key); int64_t generic_map_get_int64(generic_t x, const char* key); uint8_t generic_map_get_uint8(generic_t x, const char* key); uint16_t generic_map_get_uint16(generic_t x, const char* key); uint32_t generic_map_get_uint32(generic_t x, const char* key); uint64_t generic_map_get_uint64(generic_t x, const char* key); float generic_map_get_float(generic_t x, const char* key); double generic_map_get_double(generic_t x, const char* key); long double generic_map_get_long_double(generic_t x, const char* key); complex_float_t generic_map_get_complex_float(generic_t x, const char* key); complex_double_t generic_map_get_complex_double(generic_t x, const char* key); complex_long_double_t generic_map_get_complex_long_double(generic_t x, const char* key); char* generic_map_get_bytes(generic_t x, const char* key); char* generic_map_get_unicode(generic_t x, const char* key); /*! @brief Get a 1d array value from a map. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be returned. @param[in] subtype const char* Subtype of array expected. @param[in] precision const size_t Precision of array that is expected. @param[out] data void** Pointer to pointer that should be reallocated to store the data. @returns size_t Number of elements in the data. */ size_t generic_map_get_1darray(generic_t x, const char* key, const char *subtype, const size_t precision, void** data); size_t generic_map_get_1darray_int8(generic_t x, const char* key, int8_t** data); size_t generic_map_get_1darray_int16(generic_t x, const char* key, int16_t** data); size_t generic_map_get_1darray_int32(generic_t x, const char* key, int32_t** data); size_t generic_map_get_1darray_int64(generic_t x, const char* key, int64_t** data); size_t generic_map_get_1darray_uint8(generic_t x, const char* key, uint8_t** data); size_t generic_map_get_1darray_uint16(generic_t x, const char* key, uint16_t** data); size_t generic_map_get_1darray_uint32(generic_t x, const char* key, uint32_t** data); size_t generic_map_get_1darray_uint64(generic_t x, const char* key, uint64_t** data); size_t generic_map_get_1darray_float(generic_t x, const char* key, float** data); size_t generic_map_get_1darray_double(generic_t x, const char* key, double** data); size_t generic_map_get_1darray_long_double(generic_t x, const char* key, long double** data); size_t generic_map_get_1darray_complex_float(generic_t x, const char* key, complex_float_t** data); size_t generic_map_get_1darray_complex_double(generic_t x, const char* key, complex_double_t** data); size_t generic_map_get_1darray_complex_long_double(generic_t x, const char* key, complex_long_double_t** data); size_t generic_map_get_1darray_bytes(generic_t x, const char* key, char** data); size_t generic_map_get_1darray_unicode(generic_t x, const char* key, char** data); /*! @brief Get a nd array value from a map. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be returned. @param[in] subtype const char* Subtype of array expected. @param[in] precision const size_t Precision of array that is expected. @param[out] data void** Pointer to array that should be reallocated to store the data. @param[out] shape size_t** Pointer to array that should be reallocated to store the array shape in each dimension. @returns size_t Number of dimensions in the array. */ size_t generic_map_get_ndarray(generic_t x, const char* key, const char *subtype, const size_t precision, void** data, size_t** shape); size_t generic_map_get_ndarray_int8(generic_t x, const char* key, int8_t** data, size_t** shape); size_t generic_map_get_ndarray_int16(generic_t x, const char* key, int16_t** data, size_t** shape); size_t generic_map_get_ndarray_int32(generic_t x, const char* key, int32_t** data, size_t** shape); size_t generic_map_get_ndarray_int64(generic_t x, const char* key, int64_t** data, size_t** shape); size_t generic_map_get_ndarray_uint8(generic_t x, const char* key, uint8_t** data, size_t** shape); size_t generic_map_get_ndarray_uint16(generic_t x, const char* key, uint16_t** data, size_t** shape); size_t generic_map_get_ndarray_uint32(generic_t x, const char* key, uint32_t** data, size_t** shape); size_t generic_map_get_ndarray_uint64(generic_t x, const char* key, uint64_t** data, size_t** shape); size_t generic_map_get_ndarray_float(generic_t x, const char* key, float** data, size_t** shape); size_t generic_map_get_ndarray_double(generic_t x, const char* key, double** data, size_t** shape); size_t generic_map_get_ndarray_long_double(generic_t x, const char* key, long double** data, size_t** shape); size_t generic_map_get_ndarray_complex_float(generic_t x, const char* key, complex_float_t** data, size_t** shape); size_t generic_map_get_ndarray_complex_double(generic_t x, const char* key, complex_double_t** data, size_t** shape); size_t generic_map_get_ndarray_complex_long_double(generic_t x, const char* key, complex_long_double_t** data, size_t** shape); size_t generic_map_get_ndarray_bytes(generic_t x, const char* key, char** data, size_t** shape); size_t generic_map_get_ndarray_unicode(generic_t x, const char* key, char** data, size_t** shape); /*! @brief Set an item in an array for types that don't require additional parameters. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be set. @param[in] type const char* Type of value being set. @param[in] value void* Pointer to data that item should be set to. @returns int -1 if there is an error, 0 otherwise. */ int generic_array_set_item(generic_t x, const size_t index, const char *type, void* value); int generic_array_set_bool(generic_t x, const size_t index, bool value); int generic_array_set_integer(generic_t x, const size_t index, int value); int generic_array_set_null(generic_t x, const size_t index, void* value); int generic_array_set_number(generic_t x, const size_t index, double value); int generic_array_set_string(generic_t x, const size_t index, char* value); int generic_array_set_object(generic_t x, const size_t index, generic_t value); int generic_array_set_map(generic_t x, const size_t index, generic_t value); int generic_array_set_array(generic_t x, const size_t index, generic_t value); int generic_array_set_direct(generic_t x, const size_t index, char* value); int generic_array_set_ply(generic_t x, const size_t index, ply_t value); int generic_array_set_obj(generic_t x, const size_t index, obj_t value); int generic_array_set_python_class(generic_t x, const size_t index, python_t value); int generic_array_set_python_function(generic_t x, const size_t index, python_t value); int generic_array_set_schema(generic_t x, const size_t index, schema_t value); int generic_array_set_any(generic_t x, const size_t index, generic_t value); /*! @brief Set a scalar value in an array. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be set. @param[in] value void* Pointer to scalar data. @param[in] subtype const char* Subtype of scalar in value. @param[in] precision const int Precision of scalar in value. @param[in] units const char* Units of value. @returns int -1 if there is an error, 0 otherwise. */ int generic_array_set_scalar(generic_t x, const size_t index, void* value, const char *subtype, const size_t precision, const char* units); int generic_array_set_int8(generic_t x, const size_t index, int8_t value, const char* units); int generic_array_set_int16(generic_t x, const size_t index, int16_t value, const char* units); int generic_array_set_int32(generic_t x, const size_t index, int32_t value, const char* units); int generic_array_set_int64(generic_t x, const size_t index, int64_t value, const char* units); int generic_array_set_uint8(generic_t x, const size_t index, uint8_t value, const char* units); int generic_array_set_uint16(generic_t x, const size_t index, uint16_t value, const char* units); int generic_array_set_uint32(generic_t x, const size_t index, uint32_t value, const char* units); int generic_array_set_uint64(generic_t x, const size_t index, uint64_t value, const char* units); int generic_array_set_float(generic_t x, const size_t index, float value, const char* units); int generic_array_set_double(generic_t x, const size_t index, double value, const char* units); int generic_array_set_long_double(generic_t x, const size_t index, long double value, const char* units); int generic_array_set_complex_float(generic_t x, const size_t index, complex_float_t value, const char* units); int generic_array_set_complex_double(generic_t x, const size_t index, complex_double_t value, const char* units); int generic_array_set_complex_long_double(generic_t x, const size_t index, complex_long_double_t value, const char* units); int generic_array_set_bytes(generic_t x, const size_t index, char* value, const char* units); int generic_array_set_unicode(generic_t x, const size_t index, char* value, const char* units); /*! @brief Set a 1d array value in an array. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be set. @param[in] value void* Pointer to array data. @param[in] subtype const char* Subtype of array expected. @param[in] precision const size_t Precision of array that is expected. @param[in] length const size_t Number of elements in value. @param[in] units const char* Units of value. @returns int -1 if there is an error, 0 otherwise. */ int generic_array_set_1darray(generic_t x, const size_t index, void* value, const char *subtype, const size_t precision, const size_t length, const char* units); int generic_array_set_1darray_int8(generic_t x, const size_t index, int8_t* value, const size_t length, const char* units); int generic_array_set_1darray_int16(generic_t x, const size_t index, int16_t* value, const size_t length, const char* units); int generic_array_set_1darray_int32(generic_t x, const size_t index, int32_t* value, const size_t length, const char* units); int generic_array_set_1darray_int64(generic_t x, const size_t index, int64_t* value, const size_t length, const char* units); int generic_array_set_1darray_uint8(generic_t x, const size_t index, uint8_t* value, const size_t length, const char* units); int generic_array_set_1darray_uint16(generic_t x, const size_t index, uint16_t* value, const size_t length, const char* units); int generic_array_set_1darray_uint32(generic_t x, const size_t index, uint32_t* value, const size_t length, const char* units); int generic_array_set_1darray_uint64(generic_t x, const size_t index, uint64_t* value, const size_t length, const char* units); int generic_array_set_1darray_float(generic_t x, const size_t index, float* value, const size_t length, const char* units); int generic_array_set_1darray_double(generic_t x, const size_t index, double* value, const size_t length, const char* units); int generic_array_set_1darray_long_double(generic_t x, const size_t index, long double* value, const size_t length, const char* units); int generic_array_set_1darray_complex_float(generic_t x, const size_t index, complex_float_t* value, const size_t length, const char* units); int generic_array_set_1darray_complex_double(generic_t x, const size_t index, complex_double_t* value, const size_t length, const char* units); int generic_array_set_1darray_complex_long_double(generic_t x, const size_t index, complex_long_double_t* value, const size_t length, const char* units); int generic_array_set_1darray_bytes(generic_t x, const size_t index, char** value, const size_t length, const char* units); int generic_array_set_1darray_unicode(generic_t x, const size_t index, char** value, const size_t length, const char* units); /*! @brief Set a nd array value from an array. @param[in] x generic_t Generic object that is presumed to contain an array. @param[in] index size_t Index for value that should be set. @param[in] value void* Pointer to array data. @param[in] subtype const char* Subtype of array in value. @param[in] precision const size_t Precision of array that is in value. @param[in] ndim size_t Number of dimensions in the array. @param[in] shape size_t* Pointer to array containing the size of the array in each dimension. @returns int -1 if there is an error, 0 otherwise. */ int generic_array_set_ndarray(generic_t x, const size_t index, void* data, const char *subtype, const size_t precision, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_int8(generic_t x, const size_t index, int8_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_int16(generic_t x, const size_t index, int16_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_int32(generic_t x, const size_t index, int32_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_int64(generic_t x, const size_t index, int64_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_uint8(generic_t x, const size_t index, uint8_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_uint16(generic_t x, const size_t index, uint16_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_uint32(generic_t x, const size_t index, uint32_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_uint64(generic_t x, const size_t index, uint64_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_float(generic_t x, const size_t index, float* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_double(generic_t x, const size_t index, double* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_long_double(generic_t x, const size_t index, long double* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_complex_float(generic_t x, const size_t index, complex_float_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_complex_double(generic_t x, const size_t index, complex_double_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_complex_long_double(generic_t x, const size_t index, complex_long_double_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_bytes(generic_t x, const size_t index, char** data, const size_t ndim, const size_t* shape, const char* units); int generic_array_set_ndarray_unicode(generic_t x, const size_t index, char** data, const size_t ndim, const size_t* shape, const char* units); /*! @brief Set an item from a map for types that don't require additional parameters. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be set. @param[in] type const char* Type of value being set. @param[in] value void* Pointer to data that item should be set to. @returns int -1 if there is an error, 0 otherwise. */ int generic_map_set_item(generic_t x, const char* key, const char* type, void* value); int generic_map_set_bool(generic_t x, const char* key, bool value); int generic_map_set_integer(generic_t x, const char* key, int value); int generic_map_set_null(generic_t x, const char* key, void* value); int generic_map_set_number(generic_t x, const char* key, double value); int generic_map_set_string(generic_t x, const char* key, char* value); int generic_map_set_object(generic_t x, const char* key, generic_t value); int generic_map_set_map(generic_t x, const char* key, generic_t value); int generic_map_set_array(generic_t x, const char* key, generic_t value); int generic_map_set_direct(generic_t x, const char* key, char* value); int generic_map_set_ply(generic_t x, const char* key, ply_t value); int generic_map_set_obj(generic_t x, const char* key, obj_t value); int generic_map_set_python_class(generic_t x, const char* key, python_t value); int generic_map_set_python_function(generic_t x, const char* key, python_t value); int generic_map_set_schema(generic_t x, const char* key, schema_t value); int generic_map_set_any(generic_t x, const char* key, generic_t value); /*! @brief Set a scalar value in a map. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be set. @param[in] value void* Pointer to scalar data. @param[in] subtype const char* Subtype of scalar in value. @param[in] precision const int Precision of scalar in value. @param[in] units const char* Units of value. @returns int -1 if there is an error, 0 otherwise. */ int generic_map_set_scalar(generic_t x, const char* key, void* value, const char *subtype, const size_t precision, const char* units); int generic_map_set_int8(generic_t x, const char* key, int8_t value, const char* units); int generic_map_set_int16(generic_t x, const char* key, int16_t value, const char* units); int generic_map_set_int32(generic_t x, const char* key, int32_t value, const char* units); int generic_map_set_int64(generic_t x, const char* key, int64_t value, const char* units); int generic_map_set_uint8(generic_t x, const char* key, uint8_t value, const char* units); int generic_map_set_uint16(generic_t x, const char* key, uint16_t value, const char* units); int generic_map_set_uint32(generic_t x, const char* key, uint32_t value, const char* units); int generic_map_set_uint64(generic_t x, const char* key, uint64_t value, const char* units); int generic_map_set_float(generic_t x, const char* key, float value, const char* units); int generic_map_set_double(generic_t x, const char* key, double value, const char* units); int generic_map_set_long_double(generic_t x, const char* key, long double value, const char* units); int generic_map_set_complex_float(generic_t x, const char* key, complex_float_t value, const char* units); int generic_map_set_complex_double(generic_t x, const char* key, complex_double_t value, const char* units); int generic_map_set_complex_long_double(generic_t x, const char* key, complex_long_double_t value, const char* units); int generic_map_set_bytes(generic_t x, const char* key, char* value, const char* units); int generic_map_set_unicode(generic_t x, const char* key, char* value, const char* units); /*! @brief Set a 1d array value in a map. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be set. @param[in] value void* Pointer to array data. @param[in] subtype const char* Subtype of array expected. @param[in] precision const size_t Precision of array that is expected. @param[in] length const size_t Number of elements in value. @param[in] units const char* Units of value. @returns int -1 if there is an error, 0 otherwise. */ int generic_map_set_1darray(generic_t x, const char* key, void* value, const char *subtype, const size_t precision, const size_t length, const char* units); int generic_map_set_1darray_int8(generic_t x, const char* key, int8_t* value, const size_t length, const char* units); int generic_map_set_1darray_int16(generic_t x, const char* key, int16_t* value, const size_t length, const char* units); int generic_map_set_1darray_int32(generic_t x, const char* key, int32_t* value, const size_t length, const char* units); int generic_map_set_1darray_int64(generic_t x, const char* key, int64_t* value, const size_t length, const char* units); int generic_map_set_1darray_uint8(generic_t x, const char* key, uint8_t* value, const size_t length, const char* units); int generic_map_set_1darray_uint16(generic_t x, const char* key, uint16_t* value, const size_t length, const char* units); int generic_map_set_1darray_uint32(generic_t x, const char* key, uint32_t* value, const size_t length, const char* units); int generic_map_set_1darray_uint64(generic_t x, const char* key, uint64_t* value, const size_t length, const char* units); int generic_map_set_1darray_float(generic_t x, const char* key, float* value, const size_t length, const char* units); int generic_map_set_1darray_double(generic_t x, const char* key, double* value, const size_t length, const char* units); int generic_map_set_1darray_long_double(generic_t x, const char* key, long double* value, const size_t length, const char* units); int generic_map_set_1darray_complex_float(generic_t x, const char* key, complex_float_t* value, const size_t length, const char* units); int generic_map_set_1darray_complex_double(generic_t x, const char* key, complex_double_t* value, const size_t length, const char* units); int generic_map_set_1darray_complex_long_double(generic_t x, const char* key, complex_long_double_t* value, const size_t length, const char* units); int generic_map_set_1darray_bytes(generic_t x, const char* key, char** value, const size_t length, const char* units); int generic_map_set_1darray_unicode(generic_t x, const char* key, char** value, const size_t length, const char* units); /*! @brief Set a nd array value in a map. @param[in] x generic_t Generic object that is presumed to contain a map. @param[in] key const char* Key string for value that should be set. @param[in] value void* Pointer to array data. @param[in] subtype const char* Subtype of array in value. @param[in] precision const size_t Precision of array that is in value. @param[in] ndim size_t Number of dimensions in the array. @param[in] shape size_t* Pointer to array containing the size of the array in each dimension. @returns int -1 if there is an error, 0 otherwise. */ int generic_map_set_ndarray(generic_t x, const char* key, void* data, const char *subtype, const size_t precision, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_int8(generic_t x, const char* key, int8_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_int16(generic_t x, const char* key, int16_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_int32(generic_t x, const char* key, int32_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_int64(generic_t x, const char* key, int64_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_uint8(generic_t x, const char* key, uint8_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_uint16(generic_t x, const char* key, uint16_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_uint32(generic_t x, const char* key, uint32_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_uint64(generic_t x, const char* key, uint64_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_float(generic_t x, const char* key, float* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_double(generic_t x, const char* key, double* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_long_double(generic_t x, const char* key, long double* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_complex_float(generic_t x, const char* key, complex_float_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_complex_double(generic_t x, const char* key, complex_double_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_complex_long_double(generic_t x, const char* key, complex_long_double_t* data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_bytes(generic_t x, const char* key, char** data, const size_t ndim, const size_t* shape, const char* units); int generic_map_set_ndarray_unicode(generic_t x, const char* key, char** data, const size_t ndim, const size_t* shape, const char* units); /*! >>>>>>> topic/timesync @brief Destroy a structure containing a Python object. @param[in] x python_t* Pointer to Python object structure that should be freed. */ void destroy_python(python_t *x); /*! @brief Copy a Python object structure (NOTE: this dosn't copy the underlying Python object but does increment the reference count). @param[in] x python_t Structure containing Python object to copy. @returns python_t Copy of x. */ python_t copy_python(python_t x); /*! @brief Display a Python object structure. @param[in] x python_t Structure containing Python object to display. */ void display_python(python_t x); /*! @brief Destroy a structure containing a Python function object. @param[in] x python_function_t* Pointer to Python function structure that should be freed. */ void destroy_python_function(python_function_t *x); /*! @brief Skip datatype arguments. @param[in] dtype dtype_t* Type structure to skip arguments for. @param[in, out] nargs Pointer to number of arguments in ap. @param[in, out] ap va_list_t Variable argument list. @returns int 0 if there are no errors, 1 otherwise. */ int skip_va_elements(const dtype_t* dtype, size_t *nargs, va_list_t *ap); /*! @brief Determine if a datatype is empty. @param[in] dtype dtype_t* Type structure to test. @returns int 1 if dtype is empty, 0 otherwise. */ int is_empty_dtype(const dtype_t* dtype); /*! @brief Get the name of the type from the class. @param[in] type_class dtype_t* Type structure/class. @returns const char* Type name. */ const char* dtype_name(const dtype_t* type_class); /*! @brief Get the subtype of the type. @param[in] type_class dtype_t* Type structure/class. @returns const char* The subtype of the class, "" if there is an error. */ const char* dtype_subtype(const dtype_t* type_class); /*! @brief Get the precision of the type. @param[in] type_class dtype_t* Type structure/class. @returns const size_t The precision of the class, 0 if there is an error. */ const size_t dtype_precision(const dtype_t* type_class); /*! @brief Initialize a datatype structure including setting the type string. @param[in] dtype dtype_t* Type structure/class. @returns dtype_t* Initialized type structure/class. */ dtype_t* complete_dtype(dtype_t *dtype, const bool use_generic); /*! @brief Construct and empty type object. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_empty(const bool use_generic); /*! @brief Create a datatype based on a JSON document. @param type_doc void* Pointer to const rapidjson::Value type doc. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_doc(void* type_doc, const bool use_generic); /*! @brief Create a datatype based on a Python dictionary. @param[in] pyobj PyObject* Python dictionary. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_python(PyObject* pyobj, const bool use_generic); /*! @brief Construct a Direct type object. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_direct(const bool use_generic); /*! @brief Construct a type object for one of the default JSON types. @param[in] type char* Name of the type. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_default(const char* type, const bool use_generic); /*! @brief Construct a Scalar type object. @param[in] subtype char* Name of the scalar subtype (e.g. int, uint, float, bytes). @param[in] precision size_t Precision of the scalar in bits. @param[in] units char* Units for scalar. (e.g. "cm", "g", "" for unitless) @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_scalar(const char* subtype, const size_t precision, const char* units, const bool use_generic); /*! @brief Construct a 1D array type object. @param[in] subtype char* Name of the array subtype (e.g. int, uint, float, bytes). @param[in] precision size_t Precision of the array in bits. @param[in] length size_t Number of elements in the array. @param[in] units char* Units for array elements. (e.g. "cm", "g", "" for unitless) @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_1darray(const char* subtype, const size_t precision, const size_t length, const char* units, const bool use_generic); /*! @brief Construct a ND array type object. @param[in] subtype char* Name of the array subtype (e.g. int, uint, float, bytes). @param[in] precision size_t Precision of the array in bits. @param[in] ndim size_t Number of dimensions in the array (and therefore also the number of elements in shape). @param[in] shape size_t* Pointer to array where each element is the size of the array in that dimension. @param[in] units char* Units for array elements. (e.g. "cm", "g", "" for unitless) @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_ndarray(const char* subtype, const size_t precision, const size_t ndim, const size_t* shape, const char* units, const bool use_generic); /*! @brief Construct a ND array type object. @param[in] subtype char* Name of the array subtype (e.g. int, uint, float, bytes). @param[in] precision size_t Precision of the array in bits. @param[in] ndim size_t Number of dimensions in the array (and therefore also the number of elements in shape). @param[in] shape[] size_t Array where each element is the size of the array in that dimension. @param[in] units char* Units for array elements. (e.g. "cm", "g", "" for unitless) @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_ndarray_arr(const char* subtype, const size_t precision, const size_t ndim, const int64_t shape[], const char* units, const bool use_generic); /*! @brief Construct a JSON array type object. @param[in] nitems size_t Number of types in items. @param[in] items dtype_t** Pointer to array of types describing the array elements. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_json_array(const size_t nitems, dtype_t** items, const bool use_generic); /*! @brief Construct a JSON object type object. @param[in] nitems size_t Number of keys/types in keys and values. @param[in] keys char** Pointer to array of keys for each type. @param[in] values dtype_t** Pointer to array of types describing the values for each key. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_json_object(const size_t nitems, char** keys, dtype_t** values, const bool use_generic); /*! @brief Construct a Ply type object. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_ply(const bool use_generic); /*! @brief Construct a Obj type object. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_obj(const bool use_generic); /*! @brief Construct an AsciiTable type object. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_ascii_table(const char *format_str, const int as_array, const bool use_generic); /*! @brief Construct a type object based on the provided format string. @param[in] format_str const char* C-style format string that will be used to determine the type of elements in arrays that will be serialized/deserialized using the resulting type. @param[in] as_array int If 1, the types will be arrays. Otherwise they will be scalars. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_format(const char *format_str, const int as_array, const bool use_generic); /*! @brief Construct a type object for Python objects. @param[in] type char* Type string. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_pyobj(const char* type, const bool use_generic); /*! @brief Construct a type object for Python object instances. @param[in] class_name char* Python class name. @param[in] args_dtype dtype_t* Datatype describing the arguments creating the instance. @param[in] kwargs_dtype dtype_t* Datatype describing the keyword arguments creating the instance. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_pyinst(const char* class_name, const dtype_t* args_dtype, const dtype_t* kwargs_dtype, const bool use_generic); /*! @brief Construct a type object for a schema. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_schema(const bool use_generic); /*! @brief Construct a type object for receiving any type. @param[in] use_generic bool If true, serialized/deserialized objects will be expected to be YggGeneric classes. @returns dtype_t* Type structure/class. */ dtype_t* create_dtype_any(const bool use_generic); /*! @brief Wrapper for freeing MetaschemaType class wrapper struct. @param[in] dtype dtype_t** Wrapper struct for C++ Metaschema type class. @returns: int 0 if free was successfull, -1 if there was an error. */ int destroy_dtype(dtype_t** dtype); /*! @brief Initialize a header struct. @param[in] size size_t Size of message to be sent. @param[in] address char* Address that should be used for remainder of message following this header if it is a multipart message. @param[in] id char* Message ID. @returns comm_head_t Structure with provided information, char arrays correctly initialized to empty strings if NULLs provided. */ static inline comm_head_t init_header(const size_t size, const char *address, const char *id) { comm_head_t out; // Parameters set during read out.multipart = 0; out.bodysiz = 0; out.bodybeg = 0; out.valid = 1; out.nargs_populated = 0; out.type_in_data = 0; // Parameters sent in header out.size = size; if (address == NULL) out.address[0] = '\0'; else strncpy(out.address, address, COMMBUFFSIZ); if (id == NULL) out.id[0] = '\0'; else strncpy(out.id, id, COMMBUFFSIZ); out.response_address[0] = '\0'; out.request_id[0] = '\0'; out.zmq_reply[0] = '\0'; out.zmq_reply_worker[0] = '\0'; out.model[0] = '\0'; // Parameters that will be removed out.serializer_type = -1; out.format_str[0] = '\0'; out.as_array = 0; // Parameters used for type out.dtype = NULL; return out; }; /*! @brief Destroy a header object. @param[in] x comm_head_t* Pointer to the header that should be destroyed. @returns int 0 if successful, -1 otherwise. */ static inline int destroy_header(comm_head_t* x) { int ret = 0; if (x->dtype != NULL) { ret = destroy_dtype(&(x->dtype)); } return ret; }; /*! @brief Split header and body of message. @param[in] buf const char* Message that should be split. @param[in] buf_siz size_t Size of buf. @param[out] head const char** pointer to buffer where the extracted header should be stored. @param[out] headsiz size_t reference to memory where size of extracted header should be stored. @returns: int 0 if split is successful, -1 if there was an error. */ static inline int split_head_body(const char *buf, const size_t buf_siz, char **head, size_t *headsiz) { // Split buffer into head and body int ret; size_t sind, eind, sind_head, eind_head; sind = 0; eind = 0; #ifdef _WIN32 // Windows regex of newline is buggy UNUSED(buf_siz); size_t sind1, eind1, sind2, eind2; char re_head_tag[COMMBUFFSIZ]; sprintf(re_head_tag, "(%s)", MSG_HEAD_SEP); ret = find_match(re_head_tag, buf, &sind1, &eind1); if (ret > 0) { sind = sind1; ret = find_match(re_head_tag, buf + eind1, &sind2, &eind2); if (ret > 0) eind = eind1 + eind2; } #else // Extract just header char re_head[COMMBUFFSIZ] = MSG_HEAD_SEP; strcat(re_head, "(.*)"); strcat(re_head, MSG_HEAD_SEP); // strcat(re_head, ".*"); ret = find_match(re_head, buf, &sind, &eind); #endif if (ret < 0) { ygglog_error("split_head_body: Could not find header in '%.1000s'", buf); return -1; } else if (ret == 0) { ygglog_debug("split_head_body: No header in '%.1000s...'", buf); sind_head = 0; eind_head = 0; } else { sind_head = sind + strlen(MSG_HEAD_SEP); eind_head = eind - strlen(MSG_HEAD_SEP); } headsiz[0] = (eind_head - sind_head); char* temp = (char*)realloc(*head, *headsiz + 1); if (temp == NULL) { ygglog_error("split_head_body: Failed to reallocate header."); return -1; } *head = temp; memcpy(*head, buf + sind_head, *headsiz); (*head)[*headsiz] = '\0'; return 0; }; /*! @brief Format header to a string. @param[in] head comm_head_t* Pointer to header to be formatted. @param[out] buf char ** Pointer to buffer where header should be written. @param[in] buf_siz size_t Size of buf. @param[in] max_header_size size_t Maximum size that header can occupy before the type should be moved to the data portion of the message. @param[in] int no_type If 1, type information will not be added to the header. If 0, it will be. @returns: int Size of header written. */ int format_comm_header(comm_head_t *head, char **buf, size_t buf_siz, const size_t max_header_size, const int no_type); /*! @brief Extract type from data and updated header. @param[in] buf char** Pointer to data containing type. @param[in] buf_siz size_t Size of buf. @param[in,out] head comm_head_t* Pointer to header structure that should be updated. @returns: int -1 if there is an error, size of adjusted data that dosn't include type otherwise. */ int parse_type_in_data(char **buf, const size_t buf_siz, comm_head_t* head); /*! @brief Extract header information from a string. @param[in] buf const char* Message that header should be extracted from. @param[in] buf_siz size_t Size of buf. @returns: comm_head_t Header information structure. */ comm_head_t parse_comm_header(const char *buf, const size_t buf_siz); /*! @brief Get the ascii table data structure. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. @returns: void* Cast pointer to ascii table. */ void* dtype_ascii_table(const dtype_t* dtype); /*! @brief Get a copy of a type structure. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. @returns: dtype_t* Type class. */ dtype_t* copy_dtype(const dtype_t* dtype); /*! @brief Wrapper for updating a type object with information from another. @param[in] dtype1 dtype_t* Wrapper struct for C++ Metaschema type class that should be updated. @param[in] dtype2 dtype_t* Wrapper struct for C++ Metaschema type class that should be updated from. @returns: int 0 if successfull, -1 if there was an error. */ int update_dtype(dtype_t* dtype1, dtype_t* dtype2); /*! @brief Wrapper for updatining a type object with information from the provided variable arguments if a generic structure is present. @param[in] dtype1 dtype_t* Wrapper struct for C++ Metaschema type class that should be updated. @param[in] nargs size_t Number of arguments in ap. @param[in] ap va_list_t Variable argument list. @returns: int 0 if successfull, -1 if there was an error. */ int update_dtype_from_generic_ap(dtype_t* dtype1, size_t nargs, va_list_t ap); /*! @brief Wrapper for updating the precision of a bytes or unicode scalar type. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. @param[in] new_precision size_t New precision. @returns: int 0 if free was successfull, -1 if there was an error. */ int update_precision_dtype(const dtype_t* dtype, const size_t new_precision); /*! @brief Wrapper for deserializing from a data type. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. @param[in] buf character pointer to serialized message. @param[in] buf_siz size_t Size of buf. @param[in] allow_realloc int If 1, variables being filled are assumed to be pointers to pointers for heap memory. If 0, variables are assumed to be pointers to stack memory. If allow_realloc is set to 1, but stack variables are passed, a segfault can occur. @param[in, out] nargs int Number of arguments remaining in argument list. @param[in] ap va_list Arguments to be parsed from message. returns: int The number of populated arguments. -1 indicates an error. */ int deserialize_dtype(const dtype_t *dtype, const char *buf, const size_t buf_siz, const int allow_realloc, size_t *nargs, va_list_t ap); /*! @brief Wrapper for serializing from a data type. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. @param[in] buf character pointer to pointer to memory where serialized message should be stored. @param[in] buf_siz size_t Size of memory allocated to buf. @param[in] allow_realloc int If 1, buf will be realloced if it is not big enough to hold the serialized emssage. If 0, an error will be returned. @param[in, out] nargs int Number of arguments remaining in argument list. @param[in] ap va_list Arguments to be formatted. returns: int The length of the serialized message or -1 if there is an error. */ int serialize_dtype(const dtype_t *dtype, char **buf, size_t *buf_siz, const int allow_realloc, size_t *nargs, va_list_t ap); /*! @brief Wrapper for displaying a data type. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. @param[in] indent char* Indentation to add to display output. */ void display_dtype(const dtype_t *dtype, const char* indent); /*! @brief Wrapper for determining how many arguments a data type expects. @param[in] dtype dtype_t* Wrapper struct for C++ Metaschema type class. */ size_t nargs_exp_dtype(const dtype_t *dtype); #define free_generic destroy_generic #define init_json_object init_generic #define init_json_array init_generic #define init_schema init_generic #define free_json_object free_generic #define free_json_array free_generic #define free_schema free_generic #define copy_json_object copy_generic #define copy_json_array copy_generic #define copy_schema copy_generic #define display_json_object display_generic #define display_json_array display_generic #define display_schema display_generic #ifdef __cplusplus /* If this is a C++ compiler, end C linkage */ } #endif #endif /*DATATYPES_H_*/
3d7pt.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 7 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) /* 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])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (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); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 8; tile_size[3] = 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; const double alpha = 0.0876; const double beta = 0.0765; // 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); } } } #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 >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,12);t1++) { lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24)); ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(3*t1-1,2)),ceild(24*t2-Nz-4,8));t3<=min(min(min(floord(Nt+Ny-4,8),floord(12*t1+Ny+21,8)),floord(24*t2+Ny+20,8)),floord(24*t1-24*t2+Nz+Ny+19,8));t3++) { for (t4=max(max(max(0,ceild(3*t1-255,256)),ceild(24*t2-Nz-1020,1024)),ceild(8*t3-Ny-1020,1024));t4<=min(min(min(min(floord(Nt+Nx-4,1024),floord(12*t1+Nx+21,1024)),floord(24*t2+Nx+20,1024)),floord(8*t3+Nx+4,1024)),floord(24*t1-24*t2+Nz+Nx+19,1024));t4++) { for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),8*t3-Ny+2),1024*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),8*t3+6),1024*t4+1022),24*t1-24*t2+Nz+21);t5++) { for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(8*t3,t5+1);t7<=min(8*t3+7,t5+Ny-2);t7++) { lbv=max(1024*t4,t5+1); ubv=min(1024*t4+1023,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* 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(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* 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]); */ return 0; }
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] = 4; tile_size[1] = 4; tile_size[2] = 32; tile_size[3] = 2048; 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<=2*Nt-2;t1++) { lbp=ceild(t1+2,2); ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-12,16),ceild(4*t2-Nz-19,32));t3<=min(min(floord(4*Nt+Ny-9,32),floord(2*t1+Ny-3,32)),floord(4*t2+Ny-9,32));t3++) { for (t4=max(max(ceild(t1-1020,1024),ceild(4*t2-Nz-2035,2048)),ceild(32*t3-Ny-2035,2048));t4<=min(min(min(floord(4*Nt+Nx-9,2048),floord(2*t1+Nx-3,2048)),floord(4*t2+Nx-9,2048)),floord(32*t3+Nx+19,2048));t4++) { for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(2048*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) { for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(2048*t4,4*t5+4); ubv=min(2048*t4+2047,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; }
GB_cumsum.c
//------------------------------------------------------------------------------ // GB_cumsum: cumlative sum of an array //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Compute the cumulative sum of an array count[0:n], of size n+1 // in pseudo-MATLAB notation: // k = sum (count [0:n-1] != 0) ; // count = cumsum ([0 count[0:n-1]]) ; // That is, count [j] on input is overwritten with the value of // sum (count [0..j-1]). count [n] is implicitly zero on input. // On output, count [n] is the total sum. #include "GB.h" void GB_cumsum // compute the cumulative sum of an array ( int64_t *restrict count, // size n+1, input/output const int64_t n, int64_t *restrict kresult, // return k, if needed by the caller int nthreads ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (count != NULL) ; ASSERT (n >= 0) ; //-------------------------------------------------------------------------- // determine # of threads to use //-------------------------------------------------------------------------- #if !defined ( _OPENMP ) nthreads = 1 ; #endif if (nthreads > 1) { nthreads = GB_IMIN (nthreads, n / 1024) ; nthreads = GB_IMAX (nthreads, 1) ; } //-------------------------------------------------------------------------- // count = cumsum ([0 count[0:n-1]]) ; //-------------------------------------------------------------------------- if (kresult == NULL) { if (nthreads <= 2) { //------------------------------------------------------------------ // cumsum with one thread //------------------------------------------------------------------ int64_t s = 0 ; for (int64_t i = 0 ; i < n ; i++) { int64_t c = count [i] ; count [i] = s ; s += c ; } count [n] = s ; } else { //------------------------------------------------------------------ // cumsum with multiple threads //------------------------------------------------------------------ int64_t ws [nthreads+1] ; #pragma omp parallel num_threads(nthreads) { // each thread sums up its own part int tid = GB_OPENMP_THREAD_ID ; int64_t istart, iend ; GB_PARTITION (istart, iend, n, tid, nthreads) ; int64_t s = 0 ; for (int64_t i = istart ; i < iend ; i++) { s += count [i] ; } ws [tid] = s ; #pragma omp barrier // each thread computes the cumsum of its own part s = 0 ; for (int i = 0 ; i < tid ; i++) { s += ws [i] ; } for (int64_t i = istart ; i < iend ; i++) { int64_t c = count [i] ; count [i] = s ; s += c ; } if (iend == n) { count [n] = s ; } } } } else { if (nthreads <= 2) { //------------------------------------------------------------------ // cumsum with one thread, also compute k //------------------------------------------------------------------ int64_t k = 0 ; int64_t s = 0 ; for (int64_t i = 0 ; i < n ; i++) { int64_t c = count [i] ; if (c != 0) k++ ; count [i] = s ; s += c ; } count [n] = s ; (*kresult) = k ; } else { //------------------------------------------------------------------ // cumsum with multiple threads, also compute k //------------------------------------------------------------------ int64_t ws [nthreads+1] ; int64_t wk [nthreads+1] ; #pragma omp parallel num_threads(nthreads) { // each thread sums up its own part int tid = GB_OPENMP_THREAD_ID ; int64_t istart, iend ; GB_PARTITION (istart, iend, n, tid, nthreads) ; int64_t k = 0 ; int64_t s = 0 ; for (int64_t i = istart ; i < iend ; i++) { int64_t c = count [i] ; if (c != 0) k++ ; s += c ; } ws [tid] = s ; wk [tid] = k ; #pragma omp barrier // each thread computes the cumsum of its own part s = 0 ; for (int i = 0 ; i < tid ; i++) { s += ws [i] ; } for (int64_t i = istart ; i < iend ; i++) { int64_t c = count [i] ; count [i] = s ; s += c ; } if (iend == n) { count [n] = s ; } } int64_t k = 0 ; for (int tid = 0 ; tid < nthreads ; tid++) { k += wk [tid] ; } (*kresult) = k ; } } }
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/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/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.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(OMPC_allocator, StartLoc, EndLoc), LParenLoc(LParenLoc), Allocator(A) {} /// Build an empty clause. OMPAllocatorClause() : OMPClause(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() == OMPC_allocator; } }; /// 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>(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>(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() == 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(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(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() == 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(OMPC_final, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPFinalClause() : OMPClause(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() == 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(OMPC_num_threads, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumThreads(NumThreads) { setPreInitStmt(HelperNumThreads, CaptureRegion); } /// Build an empty clause. OMPNumThreadsClause() : OMPClause(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() == 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(OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc), Safelen(Len) {} /// Build an empty clause. explicit OMPSafelenClause() : OMPClause(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() == 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(OMPC_simdlen, StartLoc, EndLoc), LParenLoc(LParenLoc), Simdlen(Len) {} /// Build an empty clause. explicit OMPSimdlenClause() : OMPClause(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() == OMPC_simdlen; } }; /// 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(OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num) {} /// Build an empty clause. explicit OMPCollapseClause() : OMPClause(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() == 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. OpenMPDefaultClauseKind Kind = OMPC_DEFAULT_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clauses. /// /// \param K Argument of clause. void setDefaultKind(OpenMPDefaultClauseKind 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(OpenMPDefaultClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPDefaultClause() : OMPClause(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. OpenMPDefaultClauseKind 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() == 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. OpenMPProcBindClauseKind Kind = OMPC_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(OpenMPProcBindClauseKind 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(OpenMPProcBindClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPProcBindClause() : OMPClause(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. OpenMPProcBindClauseKind 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() == 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(OMPC_unified_address, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedAddressClause() : OMPClause(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() == 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(OMPC_unified_shared_memory, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedSharedMemoryClause() : OMPClause(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() == 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(OMPC_reverse_offload, StartLoc, EndLoc) {} /// Build an empty clause. OMPReverseOffloadClause() : OMPClause(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() == 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(OMPC_dynamic_allocators, StartLoc, EndLoc) {} /// Build an empty clause. OMPDynamicAllocatorsClause() : OMPClause(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() == 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(OMPC_atomic_default_mem_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPAtomicDefaultMemOrderClause() : OMPClause(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() == 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(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(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() == 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(OMPC_ordered, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num), NumberOfLoops(NumLoops) {} /// Build an empty clause. explicit OMPOrderedClause(unsigned NumLoops) : OMPClause(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() == 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(OMPC_nowait, StartLoc, EndLoc) {} /// Build an empty clause. OMPNowaitClause() : OMPClause(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() == 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(OMPC_untied, StartLoc, EndLoc) {} /// Build an empty clause. OMPUntiedClause() : OMPClause(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() == 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(OMPC_mergeable, StartLoc, EndLoc) {} /// Build an empty clause. OMPMergeableClause() : OMPClause(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() == 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(OMPC_read, StartLoc, EndLoc) {} /// Build an empty clause. OMPReadClause() : OMPClause(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() == 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(OMPC_write, StartLoc, EndLoc) {} /// Build an empty clause. OMPWriteClause() : OMPClause(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() == 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. class OMPUpdateClause : public OMPClause { public: /// Build 'update' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_update, StartLoc, EndLoc) {} /// Build an empty clause. OMPUpdateClause() : OMPClause(OMPC_update, 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() == 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(OMPC_capture, StartLoc, EndLoc) {} /// Build an empty clause. OMPCaptureClause() : OMPClause(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() == OMPC_capture; } }; /// 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(OMPC_seq_cst, StartLoc, EndLoc) {} /// Build an empty clause. OMPSeqCstClause() : OMPClause(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() == OMPC_seq_cst; } }; /// 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>(OMPC_private, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPPrivateClause(unsigned N) : OMPVarListClause<OMPPrivateClause>(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() == 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>(OMPC_firstprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPreInit(this) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFirstprivateClause(unsigned N) : OMPVarListClause<OMPFirstprivateClause>( 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() == 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; /// 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, unsigned N) : OMPVarListClause<OMPLastprivateClause>(OMPC_lastprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPLastprivateClause(unsigned N) : OMPVarListClause<OMPLastprivateClause>( 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()); } 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 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, 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); 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() == 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>(OMPC_shared, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPSharedClause(unsigned N) : OMPVarListClause<OMPSharedClause>(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() == 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; /// 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. OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPReductionClause>(OMPC_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPReductionClause(unsigned N) : OMPVarListClause<OMPReductionClause>(OMPC_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 OMPReductionClause * 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 OMPReductionClause *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<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() == 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>(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>( 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() == 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>(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>( 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() == 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>(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>(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() == 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>(OMPC_aligned, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPAlignedClause(unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(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() == 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>(OMPC_copyin, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyinClause(unsigned N) : OMPVarListClause<OMPCopyinClause>(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() == 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>(OMPC_copyprivate, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyprivateClause(unsigned N) : OMPVarListClause<OMPCopyprivateClause>( 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() == 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>(OMPC_flush, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFlushClause(unsigned N) : OMPVarListClause<OMPFlushClause>(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() == OMPC_flush; } }; /// 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>(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>(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; } 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, 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; } /// 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() == 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 number. Stmt *Device = nullptr; /// Set the device number. /// /// \param E Device number. void setDevice(Expr *E) { Device = E; } public: /// Build 'device' clause. /// /// \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 LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDeviceClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_device, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Device(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPDeviceClause() : OMPClause(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); } 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() == 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(OMPC_threads, StartLoc, EndLoc) {} /// Build an empty clause. OMPThreadsClause() : OMPClause(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() == 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(OMPC_simd, StartLoc, EndLoc) {} /// Build an empty clause. OMPSIMDClause() : OMPClause(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() == 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 { /// Expression associated with the component. Expr *AssociatedExpression = nullptr; /// 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) : AssociatedExpression(AssociatedExpression), AssociatedDeclaration( AssociatedDeclaration ? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl()) : nullptr) {} Expr *getAssociatedExpression() const { return AssociatedExpression; } 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; /// 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 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, 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) { 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() { 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 { return llvm::makeArrayRef<Expr *>( static_cast<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."); 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; // 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) : const_component_lists_iterator::iterator_adaptor_base( Components.begin()), DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()), 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; } /// 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) : const_component_lists_iterator(UniqueDecls, DeclsListNum, CumulativeListSizes, Components) { // 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 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::pair<const ValueDecl *, MappableExprComponentListRef> operator*() const { assert(ListSizeCur != ListSizeEnd && "Invalid iterator!"); return std::make_pair( *DeclCur, MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize)); } std::pair<const ValueDecl *, MappableExprComponentListRef> 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; 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()); } const_component_lists_iterator component_lists_end() const { return const_component_lists_iterator( ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(), MappableExprComponentListRef(getComponentsRef().end(), getComponentsRef().end())); } 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()); } 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(); } public: /// Number of allowed map-type-modifiers. static constexpr unsigned NumberOfModifiers = OMPC_MAP_MODIFIER_last - OMPC_MAP_MODIFIER_unknown - 1; private: /// Map-type-modifiers for the 'map' clause. OpenMPMapModifierKind MapTypeModifiers[NumberOfModifiers] = { OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown}; /// Location of map-type-modifiers for the 'map' clause. SourceLocation MapTypeModifiersLoc[NumberOfModifiers]; /// 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(OMPC_map, Locs, Sizes, &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(OMPC_map, OMPVarListLocTy(), Sizes) {} /// 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 < NumberOfModifiers && "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 < NumberOfModifiers && "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 < NumberOfModifiers && "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 < NumberOfModifiers && "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() == 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(OMPC_num_teams, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTeams(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPNumTeamsClause() : OMPClause(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() == 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(OMPC_thread_limit, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadLimit(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPThreadLimitClause() : OMPClause(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() == 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(OMPC_priority, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Priority(Priority) { setPreInitStmt(HelperPriority, CaptureRegion); } /// Build an empty clause. OMPPriorityClause() : OMPClause(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() == 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(OMPC_grainsize, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Grainsize(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPGrainsizeClause() : OMPClause(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() == 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(OMPC_nogroup, StartLoc, EndLoc) {} /// Build an empty clause. OMPNogroupClause() : OMPClause(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() == 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(OMPC_num_tasks, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTasks(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPNumTasksClause() : OMPClause(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() == 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(OMPC_hint, StartLoc, EndLoc), LParenLoc(LParenLoc), Hint(Hint) {} /// Build an empty clause. OMPHintClause() : OMPClause(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() == 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(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(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() == 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(OMPC_defaultmap, StartLoc, EndLoc), LParenLoc(LParenLoc), Modifier(M), ModifierLoc(MLoc), Kind(Kind), KindLoc(KLoc) {} /// Build an empty clause. explicit OMPDefaultmapClause() : OMPClause(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() == 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; /// Build clause with number of variables \a NumVars. /// /// \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(NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(OMPC_to, Locs, Sizes, &MapperQualifierLoc, &MapperIdInfo) {} /// 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(OMPC_to, 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 { // 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 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, 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); 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() == 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; /// Build clause with number of variables \a NumVars. /// /// \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(NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(OMPC_from, Locs, Sizes, &MapperQualifierLoc, &MapperIdInfo) {} /// 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(OMPC_from, 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 { // 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 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, 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); 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() == 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(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(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() == OMPC_use_device_ptr; } }; /// 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(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(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() == OMPC_is_device_ptr; } }; /// This class implements a simple visitor for OMPClause /// subclasses. template<class ImplClass, template <typename> class Ptr, typename RetTy> class OMPClauseVisitorBase { public: #define PTR(CLASS) typename Ptr<CLASS>::type #define DISPATCH(CLASS) \ return static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<PTR(CLASS)>(S)) #define OPENMP_CLAUSE(Name, Class) \ RetTy Visit ## Class (PTR(Class) S) { DISPATCH(Class); } #include "clang/Basic/OpenMPKinds.def" RetTy Visit(PTR(OMPClause) S) { // Top switch clause: visit each OMPClause. switch (S->getClauseKind()) { default: llvm_unreachable("Unknown clause kind!"); #define OPENMP_CLAUSE(Name, Class) \ case OMPC_ ## Name : return Visit ## Class(static_cast<PTR(Class)>(S)); #include "clang/Basic/OpenMPKinds.def" } } // Base case, ignore it. :) RetTy VisitOMPClause(PTR(OMPClause) Node) { return RetTy(); } #undef PTR #undef DISPATCH }; template <typename T> using const_ptr = typename std::add_pointer<typename std::add_const<T>::type>; template<class ImplClass, typename RetTy = void> class OMPClauseVisitor : public OMPClauseVisitorBase <ImplClass, std::add_pointer, 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); public: OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy) : OS(OS), Policy(Policy) {} #define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *S); #include "clang/Basic/OpenMPKinds.def" }; } // namespace clang #endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
scheduleg-clause.c
/* El tipo guiado es lo mismo que el tipo dinamico solo que repartimos de forma max(n/h,chunk) si tenemos 20 iteraciones y 3 hebras => n = 20, h = 3 chunk = 2 - a la primera hebra libre le damos (20/3, 2) => (round(6.66666) = 7, 2) le damos 7 => n = 20 - 7 = 13 - a la siguiente hebra libre le damos (13/3, 2) => (round(4.3333) = 4,2) => le damos 4 => n = 14 - 4 = 10 .... etc $ ./bin/scheduleg-clause 20 2 thread 0 suma a[0]=0 suma=0 thread 0 suma a[1]=1 suma=1 thread 0 suma a[2]=2 suma=3 thread 0 suma a[3]=3 suma=6 thread 0 suma a[4]=4 suma=10 thread 0 suma a[5]=5 suma=15 thread 0 suma a[6]=6 suma=21 thread 0 suma a[15]=15 suma=36 thread 0 suma a[16]=16 suma=52 thread 0 suma a[17]=17 suma=69 thread 0 suma a[18]=18 suma=87 thread 0 suma a[19]=19 suma=106 thread 2 suma a[12]=12 suma=12 thread 2 suma a[13]=13 suma=25 thread 2 suma a[14]=14 suma=39 thread 1 suma a[7]=7 suma=7 thread 1 suma a[8]=8 suma=15 thread 1 suma a[9]=9 suma=24 thread 1 suma a[10]=10 suma=34 thread 1 suma a[11]=11 suma=45 Fuera de 'parallel for' suma=106 */ #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main(int argc, char **argv) { int i, n=20,chunk,a[n],suma=0; if(argc < 3) { fprintf(stderr,"\nFalta iteraciones y/o chunk \n"); exit(-1); } n = atoi(argv[1]); if (n>20) n=20; chunk = atoi(argv[2]); for (i=0; i<n; i++) a[i] = i; //omp_set_num_threads(3); #pragma omp parallel for firstprivate(suma) lastprivate(suma) schedule(guided,chunk) for (i=0; i<n; i++){ suma = suma + a[i]; printf(" thread %d suma a[%d]=%d suma=%d \n", omp_get_thread_num(),i,a[i],suma); } printf("Fuera de 'parallel for' suma=%d\n",suma); }
singleModificado2.c
#include <stdio.h> #include <omp.h> int main(int argc, char ** argv) { int n = 9, i, a, b[n]; for (i=0; i<n; i++) b[i] = -1; #pragma omp parallel { #pragma omp single { printf("Introduce valor de inicialización a: "); scanf("%d", &a ); printf("Single ejecutada por el thread %d\n", omp_get_thread_num()); } #pragma omp for for (i=0; i<n; i++) b[i] = a; #pragma omp master { printf("Master ejecutada por el thread %d\n", omp_get_thread_num()); for (i=0; i<n; i++) printf("b[%d] = %d\t",i,b[i]); printf("\n"); } } return(0); }
kmeans_clustering.c
/*****************************************************************************/ /*IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. */ /*By downloading, copying, installing or using the software you agree */ /*to this license. If you do not agree to this license, do not download, */ /*install, copy or use the software. */ /* */ /* */ /*Copyright (c) 2005 Northwestern University */ /*All rights reserved. */ /*Redistribution of the software in source and binary forms, */ /*with or without modification, is 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 Northwestern University 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, NON-INFRINGEMENT AND */ /*FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL */ /*NORTHWESTERN UNIVERSITY OR ITS 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: kmeans_clustering.c **/ /** Description: Implementation of regular k-means clustering **/ /** algorithm **/ /** Author: Wei-keng Liao **/ /** ECE Department, Northwestern University **/ /** email: wkliao@ece.northwestern.edu **/ /** **/ /** Edited by: Jay Pisharath **/ /** Northwestern University. **/ /** **/ /** ================================================================ **/ /** **/ /** Edited by: Sang-Ha Lee **/ /** University of Virginia **/ /** **/ /** Description: No longer supports fuzzy c-means clustering; **/ /** only regular k-means clustering. **/ /** Simplified for main functionality: regular k-means **/ /** clustering. **/ /** **/ /*************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <float.h> #include <math.h> #include "kmeans.h" #define RANDOM_MAX 2147483647 #ifndef FLT_MAX #define FLT_MAX 3.40282347e+38 #endif #ifndef _NPOINTS #define _NPOINTS 819200 #endif #ifndef _UNROLLFAC_ #define _UNROLLFAC_ 100 #endif #define _NTHREADS (_NPOINTS/_UNROLLFAC_) #ifdef _OPENARC_ #if _NPOINTS == 204800 #pragma openarc #define _NPOINTS 204800 #elif _NPOINTS == 494020 #pragma openarc #define _NPOINTS 494020 #elif _NPOINTS == 819200 #pragma openarc #define _NPOINTS 819200 #endif #if _UNROLLFAC_ == 1 #pragma openarc #define _UNROLLFAC_ 1 #elif _UNROLLFAC_ == 2 #pragma openarc #define _UNROLLFAC_ 2 #elif _UNROLLFAC_ == 4 #pragma openarc #define _UNROLLFAC_ 4 #elif _UNROLLFAC_ == 5 #pragma openarc #define _UNROLLFAC_ 5 #elif _UNROLLFAC_ == 800 #pragma openarc #define _UNROLLFAC_ 800 #elif _UNROLLFAC_ == 10 #pragma openarc #define _UNROLLFAC_ 10 #elif _UNROLLFAC_ == 100 #pragma openarc #define _UNROLLFAC_ 100 #endif #pragma openarc #define _NATTRIBUTES 34 #pragma openarc #define _NCLUSTERS 5 #pragma openarc #define _NTHREADS (_NPOINTS/_UNROLLFAC_) #endif extern double wtime(void); /*----< kmeans_clustering() >---------------------------------------------*/ PAType kmeans_clustering(float feature[_NPOINTS][_NATTRIBUTES], /* in: [npoints][nfeatures] */ int nfeatures, int npoints, int nclusters, float threshold, int membership[_NPOINTS]) /* out: [npoints] */ { int i, j, k, n=0, index, loop=0; int *new_centers_len; /* [nclusters]: no. of points in each cluster */ float (*new_centers)[_NATTRIBUTES]; /* [nclusters][nfeatures] */ float (*clusters)[_NATTRIBUTES]; /* out: [nclusters][nfeatures] */ float delta; double timing; int nthreads; int (*partial_new_centers_len)[_NCLUSTERS]; float (*partial_new_centers)[_NCLUSTERS][_NATTRIBUTES]; ///////////////////////////////////////////// // Added for inlining find_nearest_point() // ///////////////////////////////////////////// int index_fnp, i_fnp; float max_dist=FLT_MAX; int i_ed; /////////////////////////////////////////////// // Added for unrolling of the parallel loop. // /////////////////////////////////////////////// int tid, ii; nthreads = npoints/_UNROLLFAC_; /* allocate space for returning variable clusters[] */ clusters = (float (*)[_NATTRIBUTES]) malloc(nclusters * nfeatures * sizeof(float)); /* randomly pick cluster centers */ for (i=0; i<nclusters; i++) { //n = (int)rand() % npoints; for (j=0; j<nfeatures; j++) clusters[i][j] = feature[n][j]; n++; } for (i=0; i<npoints; i++) membership[i] = -1; /* need to initialize new_centers_len and new_centers[0] to all 0 */ new_centers_len = (int*) calloc(nclusters, sizeof(int)); new_centers = (float (*)[_NATTRIBUTES]) calloc(nclusters * nfeatures, sizeof(float)); partial_new_centers_len = (int (*)[_NCLUSTERS]) calloc(nthreads*nclusters, sizeof(int)); partial_new_centers =(float (*)[_NCLUSTERS][_NATTRIBUTES]) calloc(nthreads*nclusters*nfeatures, sizeof(float)); printf("num of threads = %d\n", nthreads); #pragma acc data copyin (feature[0:_NPOINTS][0:_NATTRIBUTES], membership[0:_NPOINTS]) create(clusters[0:_NCLUSTERS][0:_NATTRIBUTES]) do { delta = 0.0F; #pragma acc update device(clusters) #pragma acc kernels loop gang worker independent \ private(i, index, index_fnp, max_dist) \ reduction(+:new_centers[0:_NCLUSTERS][0:_NATTRIBUTES],new_centers_len[0:_NCLUSTERS]) #pragma openarc cuda sharedRW(new_centers_len) for(tid=0; tid<nthreads; tid++) { #pragma acc loop seq for (ii=0; ii<_UNROLLFAC_; ii++) { i = tid + ii*nthreads; /* find the index of nestest cluster centers */ //index = find_nearest_point(feature[i], // nfeatures, // clusters, // nclusters); max_dist = FLT_MAX; /* find the cluster center id with min distance to pt */ for (i_fnp=0; i_fnp<nclusters; i_fnp++) { float dist; //dist = euclid_dist_2(feature[i_fnp], clusters[i_fnp], nfeatures); /* no need square root */ dist = 0.0F; for (i_ed=0; i_ed<nfeatures; i_ed++) dist += (feature[i][i_ed]-clusters[i_fnp][i_ed]) * (feature[i][i_ed]-clusters[i_fnp][i_ed]); if (dist < max_dist) { max_dist = dist; index_fnp = i_fnp; } } index = index_fnp; /* if membership changes, increase delta by 1 */ if (membership[i] != index) delta += 1.0F; /* assign the membership to object i */ membership[i] = index; /* update new cluster centers : sum of all objects located within */ new_centers_len[index]++; for (j=0; j<nfeatures; j++) new_centers[index][j] += feature[i][j]; } } /* end of #pragma omp parallel for */ /* replace old cluster centers with new_centers */ for (i=0; i<nclusters; i++) { for (j=0; j<nfeatures; j++) { if (new_centers_len[i] > 0) clusters[i][j] = new_centers[i][j] / new_centers_len[i]; new_centers[i][j] = 0.0F; /* set back to 0 */ } new_centers_len[i] = 0; /* set back to 0 */ } } while (delta > threshold && loop++ < 500); printf("loop count: %d\n", loop); free(new_centers); free(new_centers_len); return clusters; }
TailLenSoftMax.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/TailLenSoftMax.c" #else void THLENN_(TailLenSoftMax_updateOutput)( THLENNState *state, THTensor *input, THTensor *output, THIndexTensor *len) { if ((input->nDimension != 2) && (len->nDimension != 1)) { THArgCheck(0, 2, "2D tensor expected for input, 1D tensor expected for len"); } real *input_data, *output_data; THIndex_t *len_data; ptrdiff_t nframe = input->size[0], dim = input->size[1]; ptrdiff_t t; input = THTensor_(newContiguous)(input); THTensor_(resizeAs)(output, input); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); len_data = THIndexTensor_(data)(len); #pragma omp parallel for private(t) for (t = 0; t < nframe; t++) { real *input_ptr = input_data + t*dim; real *output_ptr = output_data + t*dim; real inputMax = -THInf; accreal sum; ptrdiff_t d, ld = dim - (ptrdiff_t)len_data[t]; for (d = ld; d < dim; d++) { if (input_ptr[d] >= inputMax) inputMax = input_ptr[d]; } sum = 0; for (d = ld; d < dim; d++) { real z = exp(input_ptr[d] - inputMax); output_ptr[d] = z; sum += z; } for (d = 0; d < ld; d++) { output_ptr[d] = 0; } for (d = ld; d < dim; d++) { output_ptr[d] *= 1/sum; } } THTensor_(free)(input); } void THLENN_(TailLenSoftMax_updateGradInput)( THLENNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *output, THIndexTensor *len) { THNN_CHECK_SHAPE(input, gradOutput); if ((output->nDimension != 2) && (len->nDimension != 1)) { THError("2D tensor expected for input, 1D tensor expected for len"); } real *gradInput_data, *gradOutput_data, *output_data; THIndex_t *len_data; ptrdiff_t nframe = output->size[0], dim = output->size[1]; ptrdiff_t t; gradOutput = THTensor_(newContiguous)(gradOutput); output = THTensor_(newContiguous)(output); THTensor_(resizeAs)(gradInput, output); gradInput_data = THTensor_(data)(gradInput); output_data = THTensor_(data)(output); gradOutput_data = THTensor_(data)(gradOutput); len_data = THIndexTensor_(data)(len); #pragma omp parallel for private(t) for (t = 0; t < nframe; t++) { real *gradInput_ptr = gradInput_data + t*dim; real *output_ptr = output_data + t*dim; real *gradOutput_ptr = gradOutput_data + t*dim; ptrdiff_t d, ld = dim - (ptrdiff_t)len_data[t]; accreal sum = 0; for (d = ld; d < dim; d++) sum += (accreal)gradOutput_ptr[d] * output_ptr[d]; for (d = ld; d < dim; d++) gradInput_ptr[d] = output_ptr[d] * (gradOutput_ptr[d] - sum); for (d = 0; d < ld; d++) gradInput_ptr[d] = 0; } THTensor_(free)(gradOutput); THTensor_(free)(output); } #endif
GB_binop__pair_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 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__pair_int64 // A.*B function (eWiseMult): GB_AemultB__pair_int64 // A*D function (colscale): GB_AxD__pair_int64 // D*A function (rowscale): GB_DxB__pair_int64 // C+=B function (dense accum): GB_Cdense_accumB__pair_int64 // C+=b function (dense accum): GB_Cdense_accumb__pair_int64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pair_int64 // C=scalar+B (none) // C=scalar+B' (none) // C=A+scalar (none) // C=A'+scalar (none) // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = 1 #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) \ ; // bij = Bx [pB] #define GB_GETB(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, i, j) \ z = 1 ; // 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_PAIR || GxB_NO_INT64 || GxB_NO_PAIR_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__pair_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__pair_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__pair_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__pair_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__pair_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 //------------------------------------------------------------------------------ #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__pair_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 *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__pair_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 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 //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( 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 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++) { 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 (none) ( 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 ; 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 ; ; ; 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 (none) ( 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 \ 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 } #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 (none) ( 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 int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
mds_cython.c
/* Generated by Cython 0.29.24 */ #ifndef PY_SSIZE_T_CLEAN #define PY_SSIZE_T_CLEAN #endif /* PY_SSIZE_T_CLEAN */ #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 < 0x03030000) #error Cython requires Python 2.6+ or Python 3.3+. #else #define CYTHON_ABI "0_29_24" #define CYTHON_HEX_VERSION 0x001D18F0 #define CYTHON_FUTURE_DIVISION 1 #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 #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x02070000 #define HAVE_LONG_LONG #endif #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_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #if PY_VERSION_HEX < 0x03050000 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) #endif #ifndef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) #endif #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #ifdef SIZEOF_VOID_P enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; #endif #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #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 #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 #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int32 uint32_t; #endif #endif #else #include <stdint.h> #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) && __cplusplus >= 201103L #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__ ) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif 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 #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" #if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #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) #endif #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_STACKLESS #define METH_STACKLESS 0 #endif #if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 #define PyMem_RawMalloc(n) PyMem_Malloc(n) #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) #define PyMem_RawFree(p) PyMem_Free(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x03060000 #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #elif PY_VERSION_HEX >= 0x03000000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #else #define __Pyx_PyThreadState_Current _PyThreadState_Current #endif #if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) #include "pythread.h" #define Py_tss_NEEDS_INIT 0 typedef int Py_tss_t; static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { *key = PyThread_create_key(); return 0; } static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); *key = Py_tss_NEEDS_INIT; return key; } static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { PyObject_Free(key); } static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { return *key != Py_tss_NEEDS_INIT; } static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { PyThread_delete_key(*key); *key = Py_tss_NEEDS_INIT; } static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { return PyThread_set_key_value(*key, value); } static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { return PyThread_get_key_value(*key); } #endif #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION #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 #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS #define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) #else #define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #if defined(PyUnicode_IS_READY) #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #else #define __Pyx_PyUnicode_READY(op) (0) #endif #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_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #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) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #endif #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) #endif #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #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_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #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])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #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) #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)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? 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 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #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 #ifndef PyObject_Unicode #define PyObject_Unicode PyObject_Str #endif #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 #if PY_VERSION_HEX >= 0x030900A4 #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) #else #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) #endif #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) #else #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #endif #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) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef __Pyx_PyAsyncMethodsStruct typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_MARK_ERR_POS(f_index, lineno) \ { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } #define __PYX_ERR(f_index, lineno, Ln_error) \ { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__mds_cython #define __PYX_HAVE_API__mds_cython /* Early includes */ #include <string.h> #include <stdio.h> #include <math.h> #include "numpy/arrayobject.h" #include "numpy/ndarrayobject.h" #include "numpy/ndarraytypes.h" #include "numpy/arrayscalars.h" #include "numpy/ufuncobject.h" /* NumPy API declarations from "numpy/__init__.pxd" */ #include "pythread.h" #include <stdlib.h> #include "pystate.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const 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_UTF8 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #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 int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { return (size_t) i < (size_t) limit; } #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const 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_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const 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) 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); } #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_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #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 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(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) + 1); 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 CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* Header.proto */ #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[] = { "mds_cython.pyx", "array.pxd", "__init__.pxd", "stringsource", "type.pxd", }; /* MemviewSliceStruct.proto */ 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; #define __Pyx_MemoryView_Len(m) (m.shape[0]) /* Atomics.proto */ #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 && defined(_MSC_VER) && 0 #include <Windows.h> #undef __pyx_atomic_int_type #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 #pragma message ("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 /* NoFastGil.proto */ #define __Pyx_PyGILState_Ensure PyGILState_Ensure #define __Pyx_PyGILState_Release PyGILState_Release #define __Pyx_FastGIL_Remember() #define __Pyx_FastGIL_Forget() #define __Pyx_FastGilFuncInit() /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* BufferFormatStructs.proto */ #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; /* "scipy/linalg/cython_lapack.pxd":15 * # The original libraries should be linked directly. * * ctypedef float s # <<<<<<<<<<<<<< * ctypedef double d * ctypedef float complex c */ typedef float __pyx_t_5scipy_6linalg_13cython_lapack_s; /* "scipy/linalg/cython_lapack.pxd":16 * * ctypedef float s * ctypedef double d # <<<<<<<<<<<<<< * ctypedef float complex c * ctypedef double complex z */ typedef double __pyx_t_5scipy_6linalg_13cython_lapack_d; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":690 * # 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":691 * * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":692 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":693 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":697 * #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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":698 * * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":699 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":700 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":704 * #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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":705 * * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":714 * # 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":715 * # 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":716 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":718 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":719 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":720 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":722 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":723 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":725 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":726 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":727 * 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; /* Declarations.proto */ #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 static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* Declarations.proto */ #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 static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /*--- Type declarations ---*/ #ifndef _ARRAYARRAY_H struct arrayobject; typedef struct arrayobject arrayobject; #endif struct __pyx_array_obj; struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; /* "scipy/linalg/cython_lapack.pxd":22 * # Function pointer type declarations for * # gees and gges families of functions. * ctypedef bint cselect1(c*) # <<<<<<<<<<<<<< * ctypedef bint cselect2(c*, c*) * ctypedef bint dselect2(d*, d*) */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_cselect1(__pyx_t_float_complex *); /* "scipy/linalg/cython_lapack.pxd":23 * # gees and gges families of functions. * ctypedef bint cselect1(c*) * ctypedef bint cselect2(c*, c*) # <<<<<<<<<<<<<< * ctypedef bint dselect2(d*, d*) * ctypedef bint dselect3(d*, d*, d*) */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_cselect2(__pyx_t_float_complex *, __pyx_t_float_complex *); /* "scipy/linalg/cython_lapack.pxd":24 * ctypedef bint cselect1(c*) * ctypedef bint cselect2(c*, c*) * ctypedef bint dselect2(d*, d*) # <<<<<<<<<<<<<< * ctypedef bint dselect3(d*, d*, d*) * ctypedef bint sselect2(s*, s*) */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_dselect2(__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *); /* "scipy/linalg/cython_lapack.pxd":25 * ctypedef bint cselect2(c*, c*) * ctypedef bint dselect2(d*, d*) * ctypedef bint dselect3(d*, d*, d*) # <<<<<<<<<<<<<< * ctypedef bint sselect2(s*, s*) * ctypedef bint sselect3(s*, s*, s*) */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_dselect3(__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *); /* "scipy/linalg/cython_lapack.pxd":26 * ctypedef bint dselect2(d*, d*) * ctypedef bint dselect3(d*, d*, d*) * ctypedef bint sselect2(s*, s*) # <<<<<<<<<<<<<< * ctypedef bint sselect3(s*, s*, s*) * ctypedef bint zselect1(z*) */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_sselect2(__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *); /* "scipy/linalg/cython_lapack.pxd":27 * ctypedef bint dselect3(d*, d*, d*) * ctypedef bint sselect2(s*, s*) * ctypedef bint sselect3(s*, s*, s*) # <<<<<<<<<<<<<< * ctypedef bint zselect1(z*) * ctypedef bint zselect2(z*, z*) */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_sselect3(__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *); /* "scipy/linalg/cython_lapack.pxd":28 * ctypedef bint sselect2(s*, s*) * ctypedef bint sselect3(s*, s*, s*) * ctypedef bint zselect1(z*) # <<<<<<<<<<<<<< * ctypedef bint zselect2(z*, z*) * */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_zselect1(__pyx_t_double_complex *); /* "scipy/linalg/cython_lapack.pxd":29 * ctypedef bint sselect3(s*, s*, s*) * ctypedef bint zselect1(z*) * ctypedef bint zselect2(z*, z*) # <<<<<<<<<<<<<< * * cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) nogil */ typedef int __pyx_t_5scipy_6linalg_13cython_lapack_zselect2(__pyx_t_double_complex *, __pyx_t_double_complex *); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":729 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":730 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":731 * 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; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":733 * 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":105 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_array_obj { PyObject_HEAD struct __pyx_vtabstruct_array *__pyx_vtab; 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":279 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< * cdef object name * def __init__(self, name): */ struct __pyx_MemviewEnum_obj { PyObject_HEAD PyObject *name; }; /* "View.MemoryView":330 * * @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":965 * * @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":105 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_vtabstruct_array { PyObject *(*get_memview)(struct __pyx_array_obj *); }; static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; /* "View.MemoryView":330 * * @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":965 * * @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) --- */ /* Refnanny.proto */ #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) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* WriteUnraisableException.proto */ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback, int nogil); /* RaiseArgTupleInvalid.proto */ 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); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* None.proto */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); /* MemviewSliceInit.proto */ #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); /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); #else #define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif /* py_abs.proto */ #if CYTHON_USE_PYLONG_INTERNALS static PyObject *__Pyx_PyLong_AbsNeg(PyObject *num); #define __Pyx_PyNumber_Absolute(x)\ ((likely(PyLong_CheckExact(x))) ?\ (likely(Py_SIZE(x) >= 0) ? (Py_INCREF(x), (x)) : __Pyx_PyLong_AbsNeg(x)) :\ PyNumber_Absolute(x)) #else #define __Pyx_PyNumber_Absolute(x) PyNumber_Absolute(x) #endif /* PyDictVersioning.proto */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS #define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) #define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ (version_var) = __PYX_GET_DICT_VERSION(dict);\ (cache_var) = (value); #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ (VAR) = __pyx_dict_cached_value;\ } else {\ (VAR) = __pyx_dict_cached_value = (LOOKUP);\ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ }\ } static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); #else #define __PYX_GET_DICT_VERSION(dict) (0) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); #endif /* GetModuleGlobalName.proto */ #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } #define __Pyx_GetModuleGlobalNameUncached(var, name) {\ PY_UINT64_T __pyx_dict_version;\ PyObject *__pyx_dict_cached_value;\ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); #else #define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); #endif /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #define __Pyx_BUILD_ASSERT_EXPR(cond)\ (sizeof(char [1 - 2*!(cond)]) - 1) #ifndef Py_MEMBER_SIZE #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) #endif static size_t __pyx_pyframe_localsplus_offset = 0; #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets()\ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) #define __Pyx_PyFrame_GetLocalsplus(frame)\ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) #endif /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* PyObjectCall.proto */ #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 /* GetItemInt.proto */ #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 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); /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallNoArg.proto */ #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 /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* PyObjectCall2Args.proto */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); /* SliceObject.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, PyObject** py_start, PyObject** py_stop, PyObject** py_slice, int has_cstart, int has_cstop, int wraparound); /* SetItemInt.proto */ #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 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); /* GetTopmostException.proto */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); #endif /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* ArgTypeTest.proto */ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /* IncludeStringH.proto */ #include <string.h> /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* StrEquals.proto */ #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif /* None.proto */ static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* UnaryNegOverflows.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 *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ /* GetAttr.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /* ObjectGetItem.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); #else #define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) #endif /* decode_c_string_utf16.proto */ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 0; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = -1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } /* decode_c_string.proto */ 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)); /* GetAttr3.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* SwapException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) #define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ /* ListCompAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS 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); __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif /* ListExtend.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 } /* ListAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS 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); __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif /* None.proto */ static CYTHON_INLINE long __Pyx_div_long(long, long); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* HasAttr.proto */ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); /* PyObject_GenericGetAttrNoDict.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr #endif /* PyObject_GenericGetAttr.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr #endif /* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /* PyObjectGetAttrStrNoError.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); /* SetupReduce.proto */ static int __Pyx_setup_reduce(PyObject* type_obj); /* TypeImport.proto */ #ifndef __PYX_HAVE_RT_ImportType_proto #define __PYX_HAVE_RT_ImportType_proto enum __Pyx_ImportType_CheckSize { __Pyx_ImportType_CheckSize_Error = 0, __Pyx_ImportType_CheckSize_Warn = 1, __Pyx_ImportType_CheckSize_Ignore = 2 }; static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); #endif /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #else static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #endif /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __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); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); #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 /* BufferStructDeclare.proto */ 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; /* MemviewSliceIsContig.proto */ static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); /* OverlappingSlices.proto */ static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize); /* Capsule.proto */ static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); /* ArrayAPI.proto */ #ifndef _ARRAYARRAY_H #define _ARRAYARRAY_H typedef struct arraydescr { int typecode; int itemsize; PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); #if PY_MAJOR_VERSION >= 3 char *formats; #endif } arraydescr; struct arrayobject { PyObject_HEAD Py_ssize_t ob_size; union { char *ob_item; float *as_floats; double *as_doubles; int *as_ints; unsigned int *as_uints; unsigned char *as_uchars; signed char *as_schars; char *as_chars; unsigned long *as_ulongs; long *as_longs; #if PY_MAJOR_VERSION >= 3 unsigned long long *as_ulonglongs; long long *as_longlongs; #endif short *as_shorts; unsigned short *as_ushorts; Py_UNICODE *as_pyunicodes; void *as_voidptr; } data; Py_ssize_t allocated; struct arraydescr *ob_descr; PyObject *weakreflist; #if PY_MAJOR_VERSION >= 3 int ob_exports; #endif }; #ifndef NO_NEWARRAY_INLINE static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr) { arrayobject *op; size_t nbytes; if (size < 0) { PyErr_BadInternalCall(); return NULL; } nbytes = size * descr->itemsize; if (nbytes / descr->itemsize != (size_t)size) { return PyErr_NoMemory(); } op = (arrayobject *) type->tp_alloc(type, 0); if (op == NULL) { return NULL; } op->ob_descr = descr; op->allocated = size; op->weakreflist = NULL; __Pyx_SET_SIZE(op, size); if (size <= 0) { op->data.ob_item = NULL; } else { op->data.ob_item = PyMem_NEW(char, nbytes); if (op->data.ob_item == NULL) { Py_DECREF(op); return PyErr_NoMemory(); } } return (PyObject *) op; } #else PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr); #endif static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { void *items = (void*) self->data.ob_item; PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); if (items == NULL) { PyErr_NoMemory(); return -1; } self->data.ob_item = (char*) items; __Pyx_SET_SIZE(self, n); self->allocated = n; return 0; } static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { void *items = (void*) self->data.ob_item; Py_ssize_t newsize; if (n < self->allocated && n*4 > self->allocated) { __Pyx_SET_SIZE(self, n); return 0; } newsize = n + (n / 2) + 1; if (newsize <= n) { PyErr_NoMemory(); return -1; } PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); if (items == NULL) { PyErr_NoMemory(); return -1; } self->data.ob_item = (char*) items; __Pyx_SET_SIZE(self, n); self->allocated = newsize; return 0; } #endif /* IsLittleEndian.proto */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); /* BufferFormatCheck.proto */ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); /* TypeInfoCompare.proto */ static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); /* MemviewSliceValidateAndInit.proto */ 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); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dcd__double(PyObject *, int writable_flag); /* GCCDiagnostics.proto */ #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) #define __Pyx_HAS_GCC_DIAGNOSTIC #endif /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dcd__double__const__(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int__const__(PyObject *, int writable_flag); /* MemviewDtypeToObject.proto */ static CYTHON_INLINE PyObject *__pyx_memview_get_int(const char *itemp); static CYTHON_INLINE int __pyx_memview_set_int(const char *itemp, PyObject *obj); /* MemviewDtypeToObject.proto */ static CYTHON_INLINE PyObject *__pyx_memview_get_double(const char *itemp); static CYTHON_INLINE int __pyx_memview_set_double(const char *itemp, PyObject *obj); /* MemviewDtypeToObject.proto */ static CYTHON_INLINE PyObject *__pyx_memview_get_int__const__(const char *itemp); /* RealImag.proto */ #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(__cplusplus) && CYTHON_CCOMPLEX\ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #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 /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_float(a, b) ((a)==(b)) #define __Pyx_c_sum_float(a, b) ((a)+(b)) #define __Pyx_c_diff_float(a, b) ((a)-(b)) #define __Pyx_c_prod_float(a, b) ((a)*(b)) #define __Pyx_c_quot_float(a, b) ((a)/(b)) #define __Pyx_c_neg_float(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_float(z) ((z)==(float)0) #define __Pyx_c_conj_float(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_float(z) (::std::abs(z)) #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_float(z) ((z)==0) #define __Pyx_c_conj_float(z) (conjf(z)) #if 1 #define __Pyx_c_abs_float(z) (cabsf(z)) #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_double(a, b) ((a)==(b)) #define __Pyx_c_sum_double(a, b) ((a)+(b)) #define __Pyx_c_diff_double(a, b) ((a)-(b)) #define __Pyx_c_prod_double(a, b) ((a)*(b)) #define __Pyx_c_quot_double(a, b) ((a)/(b)) #define __Pyx_c_neg_double(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_double(z) ((z)==(double)0) #define __Pyx_c_conj_double(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_double(z) (::std::abs(z)) #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_double(z) ((z)==0) #define __Pyx_c_conj_double(z) (conj(z)) #if 1 #define __Pyx_c_abs_double(z) (cabs(z)) #define __Pyx_c_pow_double(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* MemviewSliceCopyTemplate.proto */ 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); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* FunctionImport.proto */ static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ 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 'cython.view' */ /* Module declarations from 'cython' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'cpython.exc' */ /* Module declarations from 'cpython.mem' */ /* Module declarations from 'array' */ /* Module declarations from 'cpython.array' */ static PyTypeObject *__pyx_ptype_7cpython_5array_array = 0; static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *, Py_ssize_t, int); /*proto*/ static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *, char *, Py_ssize_t); /*proto*/ /* Module declarations from 'scipy.linalg.cython_lapack' */ static void (*__pyx_f_5scipy_6linalg_13cython_lapack_dsyevr)(char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *); /*proto*/ /* Module declarations from 'libc.math' */ /* 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_generic = 0; static PyTypeObject *__pyx_ptype_5numpy_number = 0; static PyTypeObject *__pyx_ptype_5numpy_integer = 0; static PyTypeObject *__pyx_ptype_5numpy_signedinteger = 0; static PyTypeObject *__pyx_ptype_5numpy_unsignedinteger = 0; static PyTypeObject *__pyx_ptype_5numpy_inexact = 0; static PyTypeObject *__pyx_ptype_5numpy_floating = 0; static PyTypeObject *__pyx_ptype_5numpy_complexfloating = 0; static PyTypeObject *__pyx_ptype_5numpy_flexible = 0; static PyTypeObject *__pyx_ptype_5numpy_character = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; /* Module declarations from 'mds_cython' */ 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 int __pyx_memoryview_thread_locks_used; static PyThread_type_lock __pyx_memoryview_thread_locks[8]; static void __pyx_f_10mds_cython__dyevr(__Pyx_memviewslice, int, int, double, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ static PyObject *__pyx_f_10mds_cython_cython_dsyevr_inplace(__Pyx_memviewslice, PyObject *, PyObject *, PyObject *, int, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ static PyObject *__pyx_f_10mds_cython_double_center(__Pyx_memviewslice, int); /*proto*/ static PyObject *__pyx_f_10mds_cython_cython_cmds_fortran_inplace(__Pyx_memviewslice, int, int, __Pyx_memviewslice, int, int __pyx_skip_dispatch); /*proto*/ static PyObject *__pyx_f_10mds_cython_dist_matrix_subset(__Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ 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 PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_double__const__ = { "const double", NULL, sizeof(double const ), { 0 }, 0, 'R', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_int__const__ = { "const int", NULL, sizeof(int const ), { 0 }, 0, IS_UNSIGNED(int const ) ? 'U' : 'I', IS_UNSIGNED(int const ), 0 }; #define __Pyx_MODULE_NAME "mds_cython" extern int __pyx_module_is_main_mds_cython; int __pyx_module_is_main_mds_cython = 0; /* Implementation of 'mds_cython' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_sum; static PyObject *__pyx_builtin_map; static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_ImportError; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_Ellipsis; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; static const char __pyx_k_A[] = "A"; static const char __pyx_k_D[] = "D"; static const char __pyx_k_F[] = "F"; static const char __pyx_k_M[] = "M"; static const char __pyx_k_N[] = "N"; static const char __pyx_k_O[] = "O"; static const char __pyx_k_W[] = "W"; static const char __pyx_k_X[] = "X"; static const char __pyx_k_Y[] = "Y"; static const char __pyx_k_Z[] = "Z"; static const char __pyx_k_c[] = "c"; static const char __pyx_k_d[] = "d"; static const char __pyx_k_i[] = "i"; static const char __pyx_k_m[] = "m"; static const char __pyx_k_n[] = "n"; static const char __pyx_k_x[] = "x"; static const char __pyx_k_IL[] = "IL"; static const char __pyx_k_IU[] = "IU"; static const char __pyx_k_el[] = "el"; static const char __pyx_k_id[] = "id"; static const char __pyx_k_ni[] = "ni"; static const char __pyx_k_nj[] = "nj"; static const char __pyx_k_np[] = "np"; static const char __pyx_k_cnt[] = "cnt"; static const char __pyx_k_ind[] = "ind"; static const char __pyx_k_len[] = "len"; static const char __pyx_k_lst[] = "lst"; static const char __pyx_k_map[] = "map"; static const char __pyx_k_new[] = "__new__"; static const char __pyx_k_obj[] = "obj"; static const char __pyx_k_sum[] = "sum"; static const char __pyx_k_WORK[] = "WORK"; static const char __pyx_k_base[] = "base"; static const char __pyx_k_copy[] = "copy"; static const char __pyx_k_dict[] = "__dict__"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mode[] = "mode"; static const char __pyx_k_name[] = "name"; static const char __pyx_k_ndim[] = "ndim"; static const char __pyx_k_pack[] = "pack"; static const char __pyx_k_size[] = "size"; static const char __pyx_k_step[] = "step"; static const char __pyx_k_stop[] = "stop"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_ASCII[] = "ASCII"; static const char __pyx_k_IWORK[] = "IWORK"; static const char __pyx_k_class[] = "__class__"; static const char __pyx_k_dtype[] = "dtype"; static const char __pyx_k_empty[] = "empty"; static const char __pyx_k_error[] = "error"; static const char __pyx_k_flags[] = "flags"; static const char __pyx_k_int32[] = "int32"; static const char __pyx_k_max_n[] = "max_n"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_order[] = "order"; static const char __pyx_k_pdist[] = "pdist"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_shape[] = "shape"; static const char __pyx_k_start[] = "start"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_ISUPPZ[] = "ISUPPZ"; static const char __pyx_k_double[] = "double"; static const char __pyx_k_encode[] = "encode"; static const char __pyx_k_format[] = "format"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_name_2[] = "__name__"; static const char __pyx_k_offset[] = "offset"; static const char __pyx_k_output[] = "output"; static const char __pyx_k_pickle[] = "pickle"; static const char __pyx_k_reduce[] = "__reduce__"; static const char __pyx_k_starts[] = "starts"; static const char __pyx_k_struct[] = "struct"; static const char __pyx_k_unpack[] = "unpack"; static const char __pyx_k_update[] = "update"; static const char __pyx_k_values[] = "values"; static const char __pyx_k_ABS_TOL[] = "ABS_TOL"; static const char __pyx_k_D_reuse[] = "D_reuse"; static const char __pyx_k_FLOAT64[] = "FLOAT64"; static const char __pyx_k_float64[] = "float64"; static const char __pyx_k_fortran[] = "fortran"; static const char __pyx_k_ind_len[] = "ind_len"; static const char __pyx_k_ind_vec[] = "ind_vec"; static const char __pyx_k_local_n[] = "local_n"; static const char __pyx_k_memview[] = "memview"; static const char __pyx_k_Ellipsis[] = "Ellipsis"; static const char __pyx_k_getstate[] = "__getstate__"; static const char __pyx_k_itemsize[] = "itemsize"; static const char __pyx_k_pyx_type[] = "__pyx_type"; static const char __pyx_k_setstate[] = "__setstate__"; static const char __pyx_k_TypeError[] = "TypeError"; static const char __pyx_k_enumerate[] = "enumerate"; static const char __pyx_k_pyx_state[] = "__pyx_state"; static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; static const char __pyx_k_tolerance[] = "tolerance"; static const char __pyx_k_IndexError[] = "IndexError"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_mds_cython[] = "mds_cython"; static const char __pyx_k_pyx_result[] = "__pyx_result"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_squareform[] = "squareform"; static const char __pyx_k_ImportError[] = "ImportError"; static const char __pyx_k_MemoryError[] = "MemoryError"; static const char __pyx_k_PickleError[] = "PickleError"; static const char __pyx_k_lst_of_lsts[] = "lst_of_lsts"; static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; static const char __pyx_k_stringsource[] = "stringsource"; static const char __pyx_k_cython_dsyevr[] = "cython_dsyevr"; static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; static const char __pyx_k_asfortranarray[] = "asfortranarray"; static const char __pyx_k_mds_cython_pyx[] = "mds_cython.pyx"; static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_strided_and_direct[] = "<strided and direct>"; static const char __pyx_k_cython_cmds_parallel[] = "cython_cmds_parallel"; static const char __pyx_k_strided_and_indirect[] = "<strided and indirect>"; static const char __pyx_k_contiguous_and_direct[] = "<contiguous and direct>"; static const char __pyx_k_flatten_list_of_lists[] = "flatten_list_of_lists"; static const char __pyx_k_MemoryView_of_r_object[] = "<MemoryView of %r object>"; static const char __pyx_k_scipy_spatial_distance[] = "scipy.spatial.distance"; static const char __pyx_k_MemoryView_of_r_at_0x_x[] = "<MemoryView of %r at 0x%x>"; static const char __pyx_k_contiguous_and_indirect[] = "<contiguous and indirect>"; static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; static const char __pyx_k_strided_and_direct_or_indirect[] = "<strided and direct or indirect>"; static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; static const char __pyx_k_Incompatible_checksums_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (name))"; static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; static PyObject *__pyx_n_s_A; static PyObject *__pyx_n_s_ABS_TOL; static PyObject *__pyx_n_s_ASCII; 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_assign_to_read_only_memor; static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; static PyObject *__pyx_kp_s_Cannot_index_with_type_s; static PyObject *__pyx_n_s_D; static PyObject *__pyx_n_s_D_reuse; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; static PyObject *__pyx_n_u_F; static PyObject *__pyx_n_s_FLOAT64; static PyObject *__pyx_n_s_IL; static PyObject *__pyx_n_s_ISUPPZ; static PyObject *__pyx_n_s_IU; static PyObject *__pyx_n_s_IWORK; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; 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_M; 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_n_s_N; static PyObject *__pyx_n_b_O; static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; static PyObject *__pyx_n_s_PickleError; 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_n_s_View_MemoryView; static PyObject *__pyx_n_s_W; static PyObject *__pyx_n_s_WORK; static PyObject *__pyx_n_s_X; static PyObject *__pyx_n_s_Y; static PyObject *__pyx_n_s_Z; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_asfortranarray; 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_n_s_cline_in_traceback; static PyObject *__pyx_n_s_cnt; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_copy; static PyObject *__pyx_n_s_cython_cmds_parallel; static PyObject *__pyx_n_s_cython_dsyevr; static PyObject *__pyx_n_s_d; static PyObject *__pyx_n_s_dict; static PyObject *__pyx_n_u_double; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_dtype_is_object; static PyObject *__pyx_n_s_el; static PyObject *__pyx_n_s_empty; static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_flatten_list_of_lists; static PyObject *__pyx_n_s_float64; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; static PyObject *__pyx_n_s_getstate; 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_ind; static PyObject *__pyx_n_s_ind_len; static PyObject *__pyx_n_s_ind_vec; static PyObject *__pyx_n_s_int32; static PyObject *__pyx_n_s_itemsize; static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; static PyObject *__pyx_n_s_len; static PyObject *__pyx_n_s_local_n; static PyObject *__pyx_n_s_lst; static PyObject *__pyx_n_s_lst_of_lsts; static PyObject *__pyx_n_s_m; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_map; static PyObject *__pyx_n_s_max_n; static PyObject *__pyx_n_s_mds_cython; static PyObject *__pyx_kp_s_mds_cython_pyx; static PyObject *__pyx_n_s_memview; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_n; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_name_2; static PyObject *__pyx_n_s_ndim; static PyObject *__pyx_n_s_new; static PyObject *__pyx_n_s_ni; static PyObject *__pyx_n_s_nj; static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to; static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor; static PyObject *__pyx_n_s_obj; static PyObject *__pyx_n_s_offset; static PyObject *__pyx_n_s_order; static PyObject *__pyx_n_s_output; static PyObject *__pyx_n_s_pack; static PyObject *__pyx_n_s_pdist; static PyObject *__pyx_n_s_pickle; static PyObject *__pyx_n_s_pyx_PickleError; static PyObject *__pyx_n_s_pyx_checksum; static PyObject *__pyx_n_s_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_result; static PyObject *__pyx_n_s_pyx_state; static PyObject *__pyx_n_s_pyx_type; static PyObject *__pyx_n_s_pyx_unpickle_Enum; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_reduce; static PyObject *__pyx_n_s_reduce_cython; static PyObject *__pyx_n_s_reduce_ex; static PyObject *__pyx_n_s_scipy_spatial_distance; static PyObject *__pyx_n_s_setstate; static PyObject *__pyx_n_s_setstate_cython; static PyObject *__pyx_n_s_shape; static PyObject *__pyx_n_s_size; static PyObject *__pyx_n_s_squareform; static PyObject *__pyx_n_s_start; static PyObject *__pyx_n_s_starts; 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_kp_s_stringsource; static PyObject *__pyx_n_s_struct; static PyObject *__pyx_n_s_sum; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_tolerance; static PyObject *__pyx_kp_s_unable_to_allocate_array_data; static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; static PyObject *__pyx_n_s_unpack; static PyObject *__pyx_n_s_update; static PyObject *__pyx_n_s_values; static PyObject *__pyx_n_s_x; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_pf_10mds_cython__dyevr(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_A, int __pyx_v_IL, int __pyx_v_IU, double __pyx_v_ABS_TOL, __Pyx_memviewslice __pyx_v_W, __Pyx_memviewslice __pyx_v_WORK, __Pyx_memviewslice __pyx_v_IWORK, __Pyx_memviewslice __pyx_v_ISUPPZ, __Pyx_memviewslice __pyx_v_Z); /* proto */ static PyObject *__pyx_pf_10mds_cython_2cython_dsyevr_inplace(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_D, PyObject *__pyx_v_IL, PyObject *__pyx_v_IU, PyObject *__pyx_v_tolerance, int __pyx_v_n, __Pyx_memviewslice __pyx_v_W, __Pyx_memviewslice __pyx_v_Z); /* proto */ static PyObject *__pyx_pf_10mds_cython_4cython_dsyevr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_x, PyObject *__pyx_v_IL, PyObject *__pyx_v_IU, PyObject *__pyx_v_tolerance); /* proto */ static PyObject *__pyx_pf_10mds_cython_6cython_cmds_fortran_inplace(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_D, int __pyx_v_d, int __pyx_v_n, __Pyx_memviewslice __pyx_v_Y, int __pyx_v_offset); /* proto */ static PyObject *__pyx_pf_10mds_cython_8dist_matrix_subset(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_ind, __Pyx_memviewslice __pyx_v_D); /* proto */ static PyObject *__pyx_pf_10mds_cython_10cython_cmds_parallel(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, int __pyx_v_d, __Pyx_memviewslice __pyx_v_ind_vec, __Pyx_memviewslice __pyx_v_ind_len, int __pyx_v_max_n, __Pyx_memviewslice __pyx_v_output); /* proto */ static PyObject *__pyx_pf_10mds_cython_12flatten_list_of_lists(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_lst_of_lsts); /* proto */ static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags); /* proto */ static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__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 Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* 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 PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* 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 PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* 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_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* 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 PyObject *__pyx_float_1eneg_8; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_2; static PyObject *__pyx_int_10; static PyObject *__pyx_int_26; static PyObject *__pyx_int_184977713; static PyObject *__pyx_int_neg_1; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; 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__17; 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__18; static PyObject *__pyx_tuple__19; static PyObject *__pyx_tuple__20; static PyObject *__pyx_tuple__21; static PyObject *__pyx_tuple__23; 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_tuple__32; static PyObject *__pyx_codeobj__22; static PyObject *__pyx_codeobj__24; static PyObject *__pyx_codeobj__26; static PyObject *__pyx_codeobj__33; /* Late includes */ /* "mds_cython.pyx":21 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void _dyevr(double[::1, :] A, int IL, int IU, double ABS_TOL, double[:] W, double[:] WORK, int[:] IWORK, int[:] ISUPPZ, double[::1, :] Z): # <<<<<<<<<<<<<< * cdef int N = A.shape[0] * cdef int M = IU-IL+1 */ static PyObject *__pyx_pw_10mds_cython_1_dyevr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static void __pyx_f_10mds_cython__dyevr(__Pyx_memviewslice __pyx_v_A, int __pyx_v_IL, int __pyx_v_IU, double __pyx_v_ABS_TOL, __Pyx_memviewslice __pyx_v_W, __Pyx_memviewslice __pyx_v_WORK, __Pyx_memviewslice __pyx_v_IWORK, __Pyx_memviewslice __pyx_v_ISUPPZ, __Pyx_memviewslice __pyx_v_Z, CYTHON_UNUSED int __pyx_skip_dispatch) { int __pyx_v_N; CYTHON_UNUSED int __pyx_v_M; char *__pyx_v_JOBVS; char *__pyx_v_RNG; char *__pyx_v_UPLO; int __pyx_v_LDA; int __pyx_v_LDZ; double __pyx_v_VL; double __pyx_v_VU; int __pyx_v_INFO; int __pyx_v_N_EVALS_FOUND; int __pyx_v_LIWORK; int __pyx_v_LWORK; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __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; Py_ssize_t __pyx_t_10; Py_ssize_t __pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_dyevr", 0); /* "mds_cython.pyx":22 * @cython.wraparound(False) * cpdef void _dyevr(double[::1, :] A, int IL, int IU, double ABS_TOL, double[:] W, double[:] WORK, int[:] IWORK, int[:] ISUPPZ, double[::1, :] Z): * cdef int N = A.shape[0] # <<<<<<<<<<<<<< * cdef int M = IU-IL+1 * cdef char* JOBVS = 'V' */ __pyx_v_N = (__pyx_v_A.shape[0]); /* "mds_cython.pyx":23 * cpdef void _dyevr(double[::1, :] A, int IL, int IU, double ABS_TOL, double[:] W, double[:] WORK, int[:] IWORK, int[:] ISUPPZ, double[::1, :] Z): * cdef int N = A.shape[0] * cdef int M = IU-IL+1 # <<<<<<<<<<<<<< * cdef char* JOBVS = 'V' * cdef char* RNG = 'I' */ __pyx_v_M = ((__pyx_v_IU - __pyx_v_IL) + 1); /* "mds_cython.pyx":24 * cdef int N = A.shape[0] * cdef int M = IU-IL+1 * cdef char* JOBVS = 'V' # <<<<<<<<<<<<<< * cdef char* RNG = 'I' * cdef char* UPLO = 'U' */ __pyx_v_JOBVS = ((char *)"V"); /* "mds_cython.pyx":25 * cdef int M = IU-IL+1 * cdef char* JOBVS = 'V' * cdef char* RNG = 'I' # <<<<<<<<<<<<<< * cdef char* UPLO = 'U' * cdef int LDA = N */ __pyx_v_RNG = ((char *)"I"); /* "mds_cython.pyx":26 * cdef char* JOBVS = 'V' * cdef char* RNG = 'I' * cdef char* UPLO = 'U' # <<<<<<<<<<<<<< * cdef int LDA = N * cdef int LDZ = N */ __pyx_v_UPLO = ((char *)"U"); /* "mds_cython.pyx":27 * cdef char* RNG = 'I' * cdef char* UPLO = 'U' * cdef int LDA = N # <<<<<<<<<<<<<< * cdef int LDZ = N * cdef double VL = 0.0 */ __pyx_v_LDA = __pyx_v_N; /* "mds_cython.pyx":28 * cdef char* UPLO = 'U' * cdef int LDA = N * cdef int LDZ = N # <<<<<<<<<<<<<< * cdef double VL = 0.0 * cdef double VU = 0.0 */ __pyx_v_LDZ = __pyx_v_N; /* "mds_cython.pyx":29 * cdef int LDA = N * cdef int LDZ = N * cdef double VL = 0.0 # <<<<<<<<<<<<<< * cdef double VU = 0.0 * cdef int INFO = 0 */ __pyx_v_VL = 0.0; /* "mds_cython.pyx":30 * cdef int LDZ = N * cdef double VL = 0.0 * cdef double VU = 0.0 # <<<<<<<<<<<<<< * cdef int INFO = 0 * cdef int N_EVALS_FOUND = 0 */ __pyx_v_VU = 0.0; /* "mds_cython.pyx":31 * cdef double VL = 0.0 * cdef double VU = 0.0 * cdef int INFO = 0 # <<<<<<<<<<<<<< * cdef int N_EVALS_FOUND = 0 * cdef int LIWORK = IWORK.size */ __pyx_v_INFO = 0; /* "mds_cython.pyx":32 * cdef double VU = 0.0 * cdef int INFO = 0 * cdef int N_EVALS_FOUND = 0 # <<<<<<<<<<<<<< * cdef int LIWORK = IWORK.size * cdef int LWORK = WORK.size */ __pyx_v_N_EVALS_FOUND = 0; /* "mds_cython.pyx":33 * cdef int INFO = 0 * cdef int N_EVALS_FOUND = 0 * cdef int LIWORK = IWORK.size # <<<<<<<<<<<<<< * cdef int LWORK = WORK.size * dsyevr( */ __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_IWORK, 1, (PyObject *(*)(char *)) __pyx_memview_get_int, (int (*)(char *, PyObject *)) __pyx_memview_set_int, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_size); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_LIWORK = __pyx_t_3; /* "mds_cython.pyx":34 * cdef int N_EVALS_FOUND = 0 * cdef int LIWORK = IWORK.size * cdef int LWORK = WORK.size # <<<<<<<<<<<<<< * dsyevr( * JOBVS,RNG,UPLO,&N,&A[0,0], */ __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_WORK, 1, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 34, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_LWORK = __pyx_t_3; /* "mds_cython.pyx":36 * cdef int LWORK = WORK.size * dsyevr( * JOBVS,RNG,UPLO,&N,&A[0,0], # <<<<<<<<<<<<<< * &LDA,&VL,&VU,&IL,&IU,&ABS_TOL, * &N_EVALS_FOUND,&W[0],&Z[0,0], */ __pyx_t_4 = 0; __pyx_t_5 = 0; /* "mds_cython.pyx":38 * JOBVS,RNG,UPLO,&N,&A[0,0], * &LDA,&VL,&VU,&IL,&IU,&ABS_TOL, * &N_EVALS_FOUND,&W[0],&Z[0,0], # <<<<<<<<<<<<<< * &LDZ, &ISUPPZ[0],&WORK[0],&LWORK,&IWORK[0],&LIWORK,&INFO * ) */ __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; /* "mds_cython.pyx":39 * &LDA,&VL,&VU,&IL,&IU,&ABS_TOL, * &N_EVALS_FOUND,&W[0],&Z[0,0], * &LDZ, &ISUPPZ[0],&WORK[0],&LWORK,&IWORK[0],&LIWORK,&INFO # <<<<<<<<<<<<<< * ) * */ __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; /* "mds_cython.pyx":35 * cdef int LIWORK = IWORK.size * cdef int LWORK = WORK.size * dsyevr( # <<<<<<<<<<<<<< * JOBVS,RNG,UPLO,&N,&A[0,0], * &LDA,&VL,&VU,&IL,&IU,&ABS_TOL, */ __pyx_f_5scipy_6linalg_13cython_lapack_dsyevr(__pyx_v_JOBVS, __pyx_v_RNG, __pyx_v_UPLO, (&__pyx_v_N), (&(*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_A.data) + __pyx_t_4)) ) + __pyx_t_5 * __pyx_v_A.strides[1]) )))), (&__pyx_v_LDA), (&__pyx_v_VL), (&__pyx_v_VU), (&__pyx_v_IL), (&__pyx_v_IU), (&__pyx_v_ABS_TOL), (&__pyx_v_N_EVALS_FOUND), (&(*((double *) ( /* dim=0 */ (__pyx_v_W.data + __pyx_t_6 * __pyx_v_W.strides[0]) )))), (&(*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_Z.data) + __pyx_t_7)) ) + __pyx_t_8 * __pyx_v_Z.strides[1]) )))), (&__pyx_v_LDZ), (&(*((int *) ( /* dim=0 */ (__pyx_v_ISUPPZ.data + __pyx_t_9 * __pyx_v_ISUPPZ.strides[0]) )))), (&(*((double *) ( /* dim=0 */ (__pyx_v_WORK.data + __pyx_t_10 * __pyx_v_WORK.strides[0]) )))), (&__pyx_v_LWORK), (&(*((int *) ( /* dim=0 */ (__pyx_v_IWORK.data + __pyx_t_11 * __pyx_v_IWORK.strides[0]) )))), (&__pyx_v_LIWORK), (&__pyx_v_INFO)); /* "mds_cython.pyx":21 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void _dyevr(double[::1, :] A, int IL, int IU, double ABS_TOL, double[:] W, double[:] WORK, int[:] IWORK, int[:] ISUPPZ, double[::1, :] Z): # <<<<<<<<<<<<<< * cdef int N = A.shape[0] * cdef int M = IU-IL+1 */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_WriteUnraisable("mds_cython._dyevr", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_L0:; __Pyx_RefNannyFinishContext(); } /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_1_dyevr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_10mds_cython_1_dyevr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_A = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_IL; int __pyx_v_IU; double __pyx_v_ABS_TOL; __Pyx_memviewslice __pyx_v_W = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_WORK = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_IWORK = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_ISUPPZ = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Z = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_dyevr (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_A,&__pyx_n_s_IL,&__pyx_n_s_IU,&__pyx_n_s_ABS_TOL,&__pyx_n_s_W,&__pyx_n_s_WORK,&__pyx_n_s_IWORK,&__pyx_n_s_ISUPPZ,&__pyx_n_s_Z,0}; PyObject* values[9] = {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 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); CYTHON_FALLTHROUGH; case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); CYTHON_FALLTHROUGH; case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); CYTHON_FALLTHROUGH; case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); CYTHON_FALLTHROUGH; case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_A)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IL)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 1); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IU)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 2); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_ABS_TOL)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 3); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_W)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 4); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 5: if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_WORK)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 5); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 6: if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IWORK)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 6); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 7: if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_ISUPPZ)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 7); __PYX_ERR(0, 21, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 8: if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Z)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, 8); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_dyevr") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 9) { 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); } __pyx_v_A = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_A.memview)) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_IL = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_IL == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_IU = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_IU == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_ABS_TOL = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_ABS_TOL == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_W = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_W.memview)) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_WORK = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_WORK.memview)) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_IWORK = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[6], PyBUF_WRITABLE); if (unlikely(!__pyx_v_IWORK.memview)) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_ISUPPZ = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[7], PyBUF_WRITABLE); if (unlikely(!__pyx_v_ISUPPZ.memview)) __PYX_ERR(0, 21, __pyx_L3_error) __pyx_v_Z = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[8], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Z.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("_dyevr", 1, 9, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("mds_cython._dyevr", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10mds_cython__dyevr(__pyx_self, __pyx_v_A, __pyx_v_IL, __pyx_v_IU, __pyx_v_ABS_TOL, __pyx_v_W, __pyx_v_WORK, __pyx_v_IWORK, __pyx_v_ISUPPZ, __pyx_v_Z); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython__dyevr(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_A, int __pyx_v_IL, int __pyx_v_IU, double __pyx_v_ABS_TOL, __Pyx_memviewslice __pyx_v_W, __Pyx_memviewslice __pyx_v_WORK, __Pyx_memviewslice __pyx_v_IWORK, __Pyx_memviewslice __pyx_v_ISUPPZ, __Pyx_memviewslice __pyx_v_Z) { 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("_dyevr", 0); __Pyx_XDECREF(__pyx_r); if (unlikely(!__pyx_v_A.memview)) { __Pyx_RaiseUnboundLocalError("A"); __PYX_ERR(0, 21, __pyx_L1_error) } if (unlikely(!__pyx_v_W.memview)) { __Pyx_RaiseUnboundLocalError("W"); __PYX_ERR(0, 21, __pyx_L1_error) } if (unlikely(!__pyx_v_WORK.memview)) { __Pyx_RaiseUnboundLocalError("WORK"); __PYX_ERR(0, 21, __pyx_L1_error) } if (unlikely(!__pyx_v_IWORK.memview)) { __Pyx_RaiseUnboundLocalError("IWORK"); __PYX_ERR(0, 21, __pyx_L1_error) } if (unlikely(!__pyx_v_ISUPPZ.memview)) { __Pyx_RaiseUnboundLocalError("ISUPPZ"); __PYX_ERR(0, 21, __pyx_L1_error) } if (unlikely(!__pyx_v_Z.memview)) { __Pyx_RaiseUnboundLocalError("Z"); __PYX_ERR(0, 21, __pyx_L1_error) } __pyx_t_1 = __Pyx_void_to_None(__pyx_f_10mds_cython__dyevr(__pyx_v_A, __pyx_v_IL, __pyx_v_IU, __pyx_v_ABS_TOL, __pyx_v_W, __pyx_v_WORK, __pyx_v_IWORK, __pyx_v_ISUPPZ, __pyx_v_Z, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("mds_cython._dyevr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_A, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_W, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_WORK, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_IWORK, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_ISUPPZ, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_Z, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":43 * * * cpdef cython_dsyevr_inplace(double[::1,:] D, IL, IU, tolerance, int n, double[:] W, double[::1,:] Z): # <<<<<<<<<<<<<< * ''' * Computes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'D' */ static PyObject *__pyx_pw_10mds_cython_3cython_dsyevr_inplace(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_10mds_cython_cython_dsyevr_inplace(__Pyx_memviewslice __pyx_v_D, PyObject *__pyx_v_IL, PyObject *__pyx_v_IU, PyObject *__pyx_v_tolerance, int __pyx_v_n, __Pyx_memviewslice __pyx_v_W, __Pyx_memviewslice __pyx_v_Z, CYTHON_UNUSED int __pyx_skip_dispatch) { int __pyx_v_m; __Pyx_memviewslice __pyx_v_WORK = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_ISUPPZ = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_IWORK = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; __Pyx_memviewslice __pyx_t_10 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_11 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_12; double __pyx_t_13; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("cython_dsyevr_inplace", 0); /* "mds_cython.pyx":56 * - D will be overriden here! * ''' * assert (D.shape[0] == D.shape[1]) # <<<<<<<<<<<<<< * assert IL <= IU and IL >= 1 and IU <= D.shape[0] * cdef int m = abs(IU-IL)+1 */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!(((__pyx_v_D.shape[0]) == (__pyx_v_D.shape[1])) != 0))) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 56, __pyx_L1_error) } } #endif /* "mds_cython.pyx":57 * ''' * assert (D.shape[0] == D.shape[1]) * assert IL <= IU and IL >= 1 and IU <= D.shape[0] # <<<<<<<<<<<<<< * cdef int m = abs(IU-IL)+1 * # cdef double[:] W = np.empty((n,), np.float64) */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_2 = PyObject_RichCompare(__pyx_v_IL, __pyx_v_IU, Py_LE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 57, __pyx_L1_error) __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 57, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_3) { } else { __pyx_t_1 = __pyx_t_3; goto __pyx_L3_bool_binop_done; } __pyx_t_2 = PyObject_RichCompare(__pyx_v_IL, __pyx_int_1, Py_GE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 57, __pyx_L1_error) __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 57, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_3) { } else { __pyx_t_1 = __pyx_t_3; goto __pyx_L3_bool_binop_done; } __pyx_t_2 = PyInt_FromSsize_t((__pyx_v_D.shape[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 57, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyObject_RichCompare(__pyx_v_IU, __pyx_t_2, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 57, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 57, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __pyx_t_3; __pyx_L3_bool_binop_done:; if (unlikely(!__pyx_t_1)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 57, __pyx_L1_error) } } #endif /* "mds_cython.pyx":58 * assert (D.shape[0] == D.shape[1]) * assert IL <= IU and IL >= 1 and IU <= D.shape[0] * cdef int m = abs(IU-IL)+1 # <<<<<<<<<<<<<< * # cdef double[:] W = np.empty((n,), np.float64) * cdef double[:] WORK = np.empty((26*n,), np.float64) */ __pyx_t_4 = PyNumber_Subtract(__pyx_v_IU, __pyx_v_IL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 58, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_2 = __Pyx_PyNumber_Absolute(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 58, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyInt_AddObjC(__pyx_t_2, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 58, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 58, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_m = __pyx_t_5; /* "mds_cython.pyx":60 * cdef int m = abs(IU-IL)+1 * # cdef double[:] W = np.empty((n,), np.float64) * cdef double[:] WORK = np.empty((26*n,), np.float64) # <<<<<<<<<<<<<< * cdef int[:] ISUPPZ = np.empty((2*m,), np.int32) * cdef int[:] IWORK = np.empty((10*n,), np.int32) */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyInt_From_long((26 * __pyx_v_n)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __pyx_t_2 = 0; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = NULL; __pyx_t_5 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); __pyx_t_5 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_t_7, __pyx_t_8}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_2, __pyx_t_7, __pyx_t_8}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } else #endif { __pyx_t_9 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_2) { __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_2); __pyx_t_2 = NULL; } __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_5, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_5, __pyx_t_8); __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_9, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_10 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_4, PyBUF_WRITABLE); if (unlikely(!__pyx_t_10.memview)) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_WORK = __pyx_t_10; __pyx_t_10.memview = NULL; __pyx_t_10.data = NULL; /* "mds_cython.pyx":61 * # cdef double[:] W = np.empty((n,), np.float64) * cdef double[:] WORK = np.empty((26*n,), np.float64) * cdef int[:] ISUPPZ = np.empty((2*m,), np.int32) # <<<<<<<<<<<<<< * cdef int[:] IWORK = np.empty((10*n,), np.int32) * _dyevr(D, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) */ __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_np); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_empty); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyInt_From_long((2 * __pyx_v_m)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_6); __pyx_t_6 = 0; __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_np); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_int32); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = NULL; __pyx_t_5 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_9))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_9); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_9, function); __pyx_t_5 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_9)) { PyObject *__pyx_temp[3] = {__pyx_t_6, __pyx_t_8, __pyx_t_7}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_9, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_9)) { PyObject *__pyx_temp[3] = {__pyx_t_6, __pyx_t_8, __pyx_t_7}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_9, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; } else #endif { __pyx_t_2 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (__pyx_t_6) { __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); __pyx_t_6 = NULL; } __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_2, 0+__pyx_t_5, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_2, 1+__pyx_t_5, __pyx_t_7); __pyx_t_8 = 0; __pyx_t_7 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_t_2, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_11 = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_t_4, PyBUF_WRITABLE); if (unlikely(!__pyx_t_11.memview)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_ISUPPZ = __pyx_t_11; __pyx_t_11.memview = NULL; __pyx_t_11.data = NULL; /* "mds_cython.pyx":62 * cdef double[:] WORK = np.empty((26*n,), np.float64) * cdef int[:] ISUPPZ = np.empty((2*m,), np.int32) * cdef int[:] IWORK = np.empty((10*n,), np.int32) # <<<<<<<<<<<<<< * _dyevr(D, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) * */ __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_n_s_np); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyInt_From_long((10 * __pyx_v_n)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9); __pyx_t_9 = 0; __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_n_s_np); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s_int32); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = NULL; __pyx_t_5 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_9)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_9); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); __pyx_t_5 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_2)) { PyObject *__pyx_temp[3] = {__pyx_t_9, __pyx_t_7, __pyx_t_8}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { PyObject *__pyx_temp[3] = {__pyx_t_9, __pyx_t_7, __pyx_t_8}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } else #endif { __pyx_t_6 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (__pyx_t_9) { __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_9); __pyx_t_9 = NULL; } __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_t_8); __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_11 = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_t_4, PyBUF_WRITABLE); if (unlikely(!__pyx_t_11.memview)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_IWORK = __pyx_t_11; __pyx_t_11.memview = NULL; __pyx_t_11.data = NULL; /* "mds_cython.pyx":63 * cdef int[:] ISUPPZ = np.empty((2*m,), np.int32) * cdef int[:] IWORK = np.empty((10*n,), np.int32) * _dyevr(D, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) # <<<<<<<<<<<<<< * * # return((W[:m], Z)) */ __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_v_IL); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 63, __pyx_L1_error) __pyx_t_12 = __Pyx_PyInt_As_int(__pyx_v_IU); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 63, __pyx_L1_error) __pyx_t_13 = __pyx_PyFloat_AsDouble(__pyx_v_tolerance); if (unlikely((__pyx_t_13 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 63, __pyx_L1_error) __pyx_f_10mds_cython__dyevr(__pyx_v_D, __pyx_t_5, __pyx_t_12, __pyx_t_13, __pyx_v_W, __pyx_v_WORK, __pyx_v_IWORK, __pyx_v_ISUPPZ, __pyx_v_Z, 0); /* "mds_cython.pyx":43 * * * cpdef cython_dsyevr_inplace(double[::1,:] D, IL, IU, tolerance, int n, double[:] W, double[::1,:] Z): # <<<<<<<<<<<<<< * ''' * Computes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'D' */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_9); __PYX_XDEC_MEMVIEW(&__pyx_t_10, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_11, 1); __Pyx_AddTraceback("mds_cython.cython_dsyevr_inplace", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_WORK, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_ISUPPZ, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_IWORK, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_3cython_dsyevr_inplace(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10mds_cython_2cython_dsyevr_inplace[] = " \n\tComputes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'D' \n\n\tCalls underlying LAPACK procedure 'dyevr'\n\n\tReturns a tuple (evals, evecs) where: \n\t\tevals := a (d,)-shaped array of requested eigenvalues, in ascending order, where d = IU-IL+1\n\t\tevecs := a (n, d)-shaped array of the requested eigenvectors corresponding in order to 'evals'\n\n\tNotes:\n\t\t- D will be overriden here!\n\t"; static PyObject *__pyx_pw_10mds_cython_3cython_dsyevr_inplace(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_v_IL = 0; PyObject *__pyx_v_IU = 0; PyObject *__pyx_v_tolerance = 0; int __pyx_v_n; __Pyx_memviewslice __pyx_v_W = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Z = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("cython_dsyevr_inplace (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_D,&__pyx_n_s_IL,&__pyx_n_s_IU,&__pyx_n_s_tolerance,&__pyx_n_s_n,&__pyx_n_s_W,&__pyx_n_s_Z,0}; PyObject* values[7] = {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 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); CYTHON_FALLTHROUGH; case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); CYTHON_FALLTHROUGH; case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IL)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, 1); __PYX_ERR(0, 43, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IU)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, 2); __PYX_ERR(0, 43, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_tolerance)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, 3); __PYX_ERR(0, 43, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_n)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, 4); __PYX_ERR(0, 43, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 5: if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_W)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, 5); __PYX_ERR(0, 43, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 6: if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Z)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, 6); __PYX_ERR(0, 43, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cython_dsyevr_inplace") < 0)) __PYX_ERR(0, 43, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 7) { 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); } __pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_D.memview)) __PYX_ERR(0, 43, __pyx_L3_error) __pyx_v_IL = values[1]; __pyx_v_IU = values[2]; __pyx_v_tolerance = values[3]; __pyx_v_n = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_n == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 43, __pyx_L3_error) __pyx_v_W = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_W.memview)) __PYX_ERR(0, 43, __pyx_L3_error) __pyx_v_Z = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[6], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Z.memview)) __PYX_ERR(0, 43, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("cython_dsyevr_inplace", 1, 7, 7, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 43, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("mds_cython.cython_dsyevr_inplace", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10mds_cython_2cython_dsyevr_inplace(__pyx_self, __pyx_v_D, __pyx_v_IL, __pyx_v_IU, __pyx_v_tolerance, __pyx_v_n, __pyx_v_W, __pyx_v_Z); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython_2cython_dsyevr_inplace(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_D, PyObject *__pyx_v_IL, PyObject *__pyx_v_IU, PyObject *__pyx_v_tolerance, int __pyx_v_n, __Pyx_memviewslice __pyx_v_W, __Pyx_memviewslice __pyx_v_Z) { 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("cython_dsyevr_inplace", 0); __Pyx_XDECREF(__pyx_r); if (unlikely(!__pyx_v_D.memview)) { __Pyx_RaiseUnboundLocalError("D"); __PYX_ERR(0, 43, __pyx_L1_error) } if (unlikely(!__pyx_v_W.memview)) { __Pyx_RaiseUnboundLocalError("W"); __PYX_ERR(0, 43, __pyx_L1_error) } if (unlikely(!__pyx_v_Z.memview)) { __Pyx_RaiseUnboundLocalError("Z"); __PYX_ERR(0, 43, __pyx_L1_error) } __pyx_t_1 = __pyx_f_10mds_cython_cython_dsyevr_inplace(__pyx_v_D, __pyx_v_IL, __pyx_v_IU, __pyx_v_tolerance, __pyx_v_n, __pyx_v_W, __pyx_v_Z, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 43, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("mds_cython.cython_dsyevr_inplace", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_D, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_W, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_Z, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":67 * # return((W[:m], Z)) * * def cython_dsyevr(x, IL, IU, tolerance): # <<<<<<<<<<<<<< * ''' * Computes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'x' */ /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_5cython_dsyevr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10mds_cython_4cython_dsyevr[] = " \n\tComputes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'x' \n\n\tCalls underlying LAPACK procedure 'dyevr'\n\n\tReturns a tuple (evals, evecs) where: \n\t\tevals := a (d,)-shaped array of requested eigenvalues, in ascending order, where d = IU-IL+1\n\t\tevecs := a (n, d)-shaped array of the requested eigenvectors corresponding in order to 'evals'\n\t"; static PyMethodDef __pyx_mdef_10mds_cython_5cython_dsyevr = {"cython_dsyevr", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10mds_cython_5cython_dsyevr, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10mds_cython_4cython_dsyevr}; static PyObject *__pyx_pw_10mds_cython_5cython_dsyevr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_x = 0; PyObject *__pyx_v_IL = 0; PyObject *__pyx_v_IU = 0; PyObject *__pyx_v_tolerance = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("cython_dsyevr (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_x,&__pyx_n_s_IL,&__pyx_n_s_IU,&__pyx_n_s_tolerance,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); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IL)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr", 1, 4, 4, 1); __PYX_ERR(0, 67, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_IU)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr", 1, 4, 4, 2); __PYX_ERR(0, 67, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_tolerance)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_dsyevr", 1, 4, 4, 3); __PYX_ERR(0, 67, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cython_dsyevr") < 0)) __PYX_ERR(0, 67, __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_x = values[0]; __pyx_v_IL = values[1]; __pyx_v_IU = values[2]; __pyx_v_tolerance = values[3]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("cython_dsyevr", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 67, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("mds_cython.cython_dsyevr", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10mds_cython_4cython_dsyevr(__pyx_self, __pyx_v_x, __pyx_v_IL, __pyx_v_IU, __pyx_v_tolerance); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython_4cython_dsyevr(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_x, PyObject *__pyx_v_IL, PyObject *__pyx_v_IU, PyObject *__pyx_v_tolerance) { PyObject *__pyx_v_n = NULL; PyObject *__pyx_v_m = NULL; PyObject *__pyx_v_W = NULL; PyObject *__pyx_v_ISUPPZ = NULL; PyObject *__pyx_v_Z = NULL; PyObject *__pyx_v_WORK = NULL; PyObject *__pyx_v_IWORK = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; int __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; __Pyx_memviewslice __pyx_t_11 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_12; double __pyx_t_13; __Pyx_memviewslice __pyx_t_14 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_15 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_16 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_17 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_18 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("cython_dsyevr", 0); __Pyx_INCREF(__pyx_v_x); /* "mds_cython.pyx":77 * evecs := a (n, d)-shaped array of the requested eigenvectors corresponding in order to 'evals' * ''' * assert (x.shape[0] == x.shape[1]) # <<<<<<<<<<<<<< * assert IL <= IU and IL >= 1 and IU <= x.shape[0] * x = np.asfortranarray(x.copy()) */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyObject_RichCompare(__pyx_t_2, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (unlikely(!__pyx_t_4)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 77, __pyx_L1_error) } } #endif /* "mds_cython.pyx":78 * ''' * assert (x.shape[0] == x.shape[1]) * assert IL <= IU and IL >= 1 and IU <= x.shape[0] # <<<<<<<<<<<<<< * x = np.asfortranarray(x.copy()) * n, m = x.shape[0], abs(IU-IL)+1 */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = PyObject_RichCompare(__pyx_v_IL, __pyx_v_IU, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 78, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_5) { } else { __pyx_t_4 = __pyx_t_5; goto __pyx_L3_bool_binop_done; } __pyx_t_1 = PyObject_RichCompare(__pyx_v_IL, __pyx_int_1, Py_GE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 78, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_5) { } else { __pyx_t_4 = __pyx_t_5; goto __pyx_L3_bool_binop_done; } __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 78, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyObject_RichCompare(__pyx_v_IU, __pyx_t_3, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 78, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_4 = __pyx_t_5; __pyx_L3_bool_binop_done:; if (unlikely(!__pyx_t_4)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 78, __pyx_L1_error) } } #endif /* "mds_cython.pyx":79 * assert (x.shape[0] == x.shape[1]) * assert IL <= IU and IL >= 1 and IU <= x.shape[0] * x = np.asfortranarray(x.copy()) # <<<<<<<<<<<<<< * n, m = x.shape[0], abs(IU-IL)+1 * W = np.empty((n,), np.float64) */ __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 79, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asfortranarray); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 79, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s_copy); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 79, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_7)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_7); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); } } __pyx_t_3 = (__pyx_t_7) ? __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_t_7) : __Pyx_PyObject_CallNoArg(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 79, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_6, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 79, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_x, __pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":80 * assert IL <= IU and IL >= 1 and IU <= x.shape[0] * x = np.asfortranarray(x.copy()) * n, m = x.shape[0], abs(IU-IL)+1 # <<<<<<<<<<<<<< * W = np.empty((n,), np.float64) * ISUPPZ = np.empty((2*m,), np.int32) */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetItemInt(__pyx_t_1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyNumber_Subtract(__pyx_v_IU, __pyx_v_IL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyNumber_Absolute(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 80, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_n = __pyx_t_2; __pyx_t_2 = 0; __pyx_v_m = __pyx_t_1; __pyx_t_1 = 0; /* "mds_cython.pyx":81 * x = np.asfortranarray(x.copy()) * n, m = x.shape[0], abs(IU-IL)+1 * W = np.empty((n,), np.float64) # <<<<<<<<<<<<<< * ISUPPZ = np.empty((2*m,), np.int32) * Z = np.zeros((n, m), dtype=np.float64, order='F') */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_n); __Pyx_GIVEREF(__pyx_v_n); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_n); __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_np); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_3)) { PyObject *__pyx_temp[3] = {__pyx_t_6, __pyx_t_2, __pyx_t_7}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { PyObject *__pyx_temp[3] = {__pyx_t_6, __pyx_t_2, __pyx_t_7}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; } else #endif { __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_6) { __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_6); __pyx_t_6 = NULL; } __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_7); __pyx_t_2 = 0; __pyx_t_7 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 81, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_W = __pyx_t_1; __pyx_t_1 = 0; /* "mds_cython.pyx":82 * n, m = x.shape[0], abs(IU-IL)+1 * W = np.empty((n,), np.float64) * ISUPPZ = np.empty((2*m,), np.int32) # <<<<<<<<<<<<<< * Z = np.zeros((n, m), dtype=np.float64, order='F') * WORK, IWORK = np.empty((26*n,), np.float64), np.empty((10*n,), np.int32) */ __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyNumber_Multiply(__pyx_int_2, __pyx_v_m); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __pyx_t_3 = 0; __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_int32); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_9))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_9); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_9, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_9)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_7, __pyx_t_2}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_9, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_9)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_7, __pyx_t_2}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_9, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif { __pyx_t_6 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (__pyx_t_3) { __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); __pyx_t_3 = NULL; } __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_8, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_8, __pyx_t_2); __pyx_t_7 = 0; __pyx_t_2 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_ISUPPZ = __pyx_t_1; __pyx_t_1 = 0; /* "mds_cython.pyx":83 * W = np.empty((n,), np.float64) * ISUPPZ = np.empty((2*m,), np.int32) * Z = np.zeros((n, m), dtype=np.float64, order='F') # <<<<<<<<<<<<<< * WORK, IWORK = np.empty((26*n,), np.float64), np.empty((10*n,), np.int32) * _dyevr(x, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) */ __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_n); __Pyx_GIVEREF(__pyx_v_n); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_n); __Pyx_INCREF(__pyx_v_m); __Pyx_GIVEREF(__pyx_v_m); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_m); __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_7) < 0) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_order, __pyx_n_u_F) < 0) __PYX_ERR(0, 83, __pyx_L1_error) __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_t_6, __pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_Z = __pyx_t_7; __pyx_t_7 = 0; /* "mds_cython.pyx":84 * ISUPPZ = np.empty((2*m,), np.int32) * Z = np.zeros((n, m), dtype=np.float64, order='F') * WORK, IWORK = np.empty((26*n,), np.float64), np.empty((10*n,), np.int32) # <<<<<<<<<<<<<< * _dyevr(x, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) * return((W[:m], Z)) */ __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyNumber_Multiply(__pyx_int_26, __pyx_v_n); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); __pyx_t_1 = 0; __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float64); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_1)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_1); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_t_9, __pyx_t_2}; __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_1, __pyx_t_9, __pyx_t_2}; __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif { __pyx_t_3 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__pyx_t_1) { __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __pyx_t_1 = NULL; } __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_3, 0+__pyx_t_8, __pyx_t_9); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 1+__pyx_t_8, __pyx_t_2); __pyx_t_9 = 0; __pyx_t_2 = 0; __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_3, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyNumber_Multiply(__pyx_int_10, __pyx_v_n); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); __pyx_t_3 = 0; __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_int32); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_2)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_9, __pyx_t_1}; __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_9, __pyx_t_1}; __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif { __pyx_t_10 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); if (__pyx_t_3) { __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_3); __pyx_t_3 = NULL; } __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_8, __pyx_t_9); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_8, __pyx_t_1); __pyx_t_9 = 0; __pyx_t_1 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_10, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 84, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_WORK = __pyx_t_7; __pyx_t_7 = 0; __pyx_v_IWORK = __pyx_t_6; __pyx_t_6 = 0; /* "mds_cython.pyx":85 * Z = np.zeros((n, m), dtype=np.float64, order='F') * WORK, IWORK = np.empty((26*n,), np.float64), np.empty((10*n,), np.int32) * _dyevr(x, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) # <<<<<<<<<<<<<< * return((W[:m], Z)) * */ __pyx_t_11 = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(__pyx_v_x, PyBUF_WRITABLE); if (unlikely(!__pyx_t_11.memview)) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_8 = __Pyx_PyInt_As_int(__pyx_v_IL); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_12 = __Pyx_PyInt_As_int(__pyx_v_IU); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_13 = __pyx_PyFloat_AsDouble(__pyx_v_tolerance); if (unlikely((__pyx_t_13 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_v_W, PyBUF_WRITABLE); if (unlikely(!__pyx_t_14.memview)) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_15 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_v_WORK, PyBUF_WRITABLE); if (unlikely(!__pyx_t_15.memview)) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_16 = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_v_IWORK, PyBUF_WRITABLE); if (unlikely(!__pyx_t_16.memview)) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_17 = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_v_ISUPPZ, PyBUF_WRITABLE); if (unlikely(!__pyx_t_17.memview)) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_t_18 = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(__pyx_v_Z, PyBUF_WRITABLE); if (unlikely(!__pyx_t_18.memview)) __PYX_ERR(0, 85, __pyx_L1_error) __pyx_f_10mds_cython__dyevr(__pyx_t_11, __pyx_t_8, __pyx_t_12, __pyx_t_13, __pyx_t_14, __pyx_t_15, __pyx_t_16, __pyx_t_17, __pyx_t_18, 0); __PYX_XDEC_MEMVIEW(&__pyx_t_11, 1); __pyx_t_11.memview = NULL; __pyx_t_11.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_14, 1); __pyx_t_14.memview = NULL; __pyx_t_14.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_15, 1); __pyx_t_15.memview = NULL; __pyx_t_15.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_16, 1); __pyx_t_16.memview = NULL; __pyx_t_16.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_17, 1); __pyx_t_17.memview = NULL; __pyx_t_17.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_18, 1); __pyx_t_18.memview = NULL; __pyx_t_18.data = NULL; /* "mds_cython.pyx":86 * WORK, IWORK = np.empty((26*n,), np.float64), np.empty((10*n,), np.int32) * _dyevr(x, IL, IU, tolerance, W, WORK, IWORK, ISUPPZ, Z) * return((W[:m], Z)) # <<<<<<<<<<<<<< * * from cython cimport view */ __Pyx_XDECREF(__pyx_r); __pyx_t_6 = __Pyx_PyObject_GetSlice(__pyx_v_W, 0, 0, NULL, &__pyx_v_m, NULL, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 86, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 86, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __Pyx_INCREF(__pyx_v_Z); __Pyx_GIVEREF(__pyx_v_Z); PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_v_Z); __pyx_t_6 = 0; __pyx_r = __pyx_t_7; __pyx_t_7 = 0; goto __pyx_L0; /* "mds_cython.pyx":67 * # return((W[:m], Z)) * * def cython_dsyevr(x, IL, IU, tolerance): # <<<<<<<<<<<<<< * ''' * Computes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'x' */ /* 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_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __PYX_XDEC_MEMVIEW(&__pyx_t_11, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_14, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_15, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_16, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_17, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_18, 1); __Pyx_AddTraceback("mds_cython.cython_dsyevr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_n); __Pyx_XDECREF(__pyx_v_m); __Pyx_XDECREF(__pyx_v_W); __Pyx_XDECREF(__pyx_v_ISUPPZ); __Pyx_XDECREF(__pyx_v_Z); __Pyx_XDECREF(__pyx_v_WORK); __Pyx_XDECREF(__pyx_v_IWORK); __Pyx_XDECREF(__pyx_v_x); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":103 * @cython.wraparound(False) * @cython.cdivision(True) * cdef double_center(double[::1, :] D, int n): # <<<<<<<<<<<<<< * cdef int i, j * cdef double total = 0.0 */ static PyObject *__pyx_f_10mds_cython_double_center(__Pyx_memviewslice __pyx_v_D, int __pyx_v_n) { int __pyx_v_i; int __pyx_v_j; double __pyx_v_total; __Pyx_memviewslice __pyx_v_row_sum_view = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_col_sum_view = { 0, 0, { 0 }, { 0 }, { 0 } }; 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; __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; int __pyx_t_12; Py_ssize_t __pyx_t_13; Py_ssize_t __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("double_center", 0); /* "mds_cython.pyx":105 * cdef double_center(double[::1, :] D, int n): * cdef int i, j * cdef double total = 0.0 # <<<<<<<<<<<<<< * cdef double[:] row_sum_view = np.zeros((n,), dtype=np.float64) * cdef double[:] col_sum_view = np.zeros((n,), dtype=np.float64) */ __pyx_v_total = 0.0; /* "mds_cython.pyx":106 * cdef int i, j * cdef double total = 0.0 * cdef double[:] row_sum_view = np.zeros((n,), dtype=np.float64) # <<<<<<<<<<<<<< * cdef double[:] col_sum_view = np.zeros((n,), dtype=np.float64) * # cdef double[::1] row_sum_view = cnp.empty(n, dtype=np.float64) */ __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_n); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_5) < 0) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_5, PyBUF_WRITABLE); if (unlikely(!__pyx_t_6.memview)) __PYX_ERR(0, 106, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_row_sum_view = __pyx_t_6; __pyx_t_6.memview = NULL; __pyx_t_6.data = NULL; /* "mds_cython.pyx":107 * cdef double total = 0.0 * cdef double[:] row_sum_view = np.zeros((n,), dtype=np.float64) * cdef double[:] col_sum_view = np.zeros((n,), dtype=np.float64) # <<<<<<<<<<<<<< * # cdef double[::1] row_sum_view = cnp.empty(n, dtype=np.float64) * # cdef double[::1] col_sum_view = cnp.empty(n, dtype=np.float64) */ __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_n); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_4, PyBUF_WRITABLE); if (unlikely(!__pyx_t_6.memview)) __PYX_ERR(0, 107, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_col_sum_view = __pyx_t_6; __pyx_t_6.memview = NULL; __pyx_t_6.data = NULL; /* "mds_cython.pyx":113 * # row_sum_view[i] = 0.0 * # col_sum_view[i] = 0.0 * for i in range(n): # <<<<<<<<<<<<<< * for j in range(n): * row_sum_view[i] += D[i,j] */ __pyx_t_7 = __pyx_v_n; __pyx_t_8 = __pyx_t_7; for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_i = __pyx_t_9; /* "mds_cython.pyx":114 * # col_sum_view[i] = 0.0 * for i in range(n): * for j in range(n): # <<<<<<<<<<<<<< * row_sum_view[i] += D[i,j] * col_sum_view[j] += D[i,j] */ __pyx_t_10 = __pyx_v_n; __pyx_t_11 = __pyx_t_10; for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { __pyx_v_j = __pyx_t_12; /* "mds_cython.pyx":115 * for i in range(n): * for j in range(n): * row_sum_view[i] += D[i,j] # <<<<<<<<<<<<<< * col_sum_view[j] += D[i,j] * total += D[i,j] */ __pyx_t_13 = __pyx_v_i; __pyx_t_14 = __pyx_v_j; __pyx_t_15 = __pyx_v_i; *((double *) ( /* dim=0 */ (__pyx_v_row_sum_view.data + __pyx_t_15 * __pyx_v_row_sum_view.strides[0]) )) += (*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_13)) ) + __pyx_t_14 * __pyx_v_D.strides[1]) ))); /* "mds_cython.pyx":116 * for j in range(n): * row_sum_view[i] += D[i,j] * col_sum_view[j] += D[i,j] # <<<<<<<<<<<<<< * total += D[i,j] * for i in range(n): */ __pyx_t_14 = __pyx_v_i; __pyx_t_13 = __pyx_v_j; __pyx_t_15 = __pyx_v_j; *((double *) ( /* dim=0 */ (__pyx_v_col_sum_view.data + __pyx_t_15 * __pyx_v_col_sum_view.strides[0]) )) += (*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_14)) ) + __pyx_t_13 * __pyx_v_D.strides[1]) ))); /* "mds_cython.pyx":117 * row_sum_view[i] += D[i,j] * col_sum_view[j] += D[i,j] * total += D[i,j] # <<<<<<<<<<<<<< * for i in range(n): * row_sum_view[i] /= n */ __pyx_t_13 = __pyx_v_i; __pyx_t_14 = __pyx_v_j; __pyx_v_total = (__pyx_v_total + (*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_13)) ) + __pyx_t_14 * __pyx_v_D.strides[1]) )))); } } /* "mds_cython.pyx":118 * col_sum_view[j] += D[i,j] * total += D[i,j] * for i in range(n): # <<<<<<<<<<<<<< * row_sum_view[i] /= n * col_sum_view[i] /= n */ __pyx_t_7 = __pyx_v_n; __pyx_t_8 = __pyx_t_7; for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_i = __pyx_t_9; /* "mds_cython.pyx":119 * total += D[i,j] * for i in range(n): * row_sum_view[i] /= n # <<<<<<<<<<<<<< * col_sum_view[i] /= n * total /= (n*n) */ __pyx_t_14 = __pyx_v_i; *((double *) ( /* dim=0 */ (__pyx_v_row_sum_view.data + __pyx_t_14 * __pyx_v_row_sum_view.strides[0]) )) /= __pyx_v_n; /* "mds_cython.pyx":120 * for i in range(n): * row_sum_view[i] /= n * col_sum_view[i] /= n # <<<<<<<<<<<<<< * total /= (n*n) * for i in range(n): */ __pyx_t_14 = __pyx_v_i; *((double *) ( /* dim=0 */ (__pyx_v_col_sum_view.data + __pyx_t_14 * __pyx_v_col_sum_view.strides[0]) )) /= __pyx_v_n; } /* "mds_cython.pyx":121 * row_sum_view[i] /= n * col_sum_view[i] /= n * total /= (n*n) # <<<<<<<<<<<<<< * for i in range(n): * for j in range(n): */ __pyx_v_total = (__pyx_v_total / (__pyx_v_n * __pyx_v_n)); /* "mds_cython.pyx":122 * col_sum_view[i] /= n * total /= (n*n) * for i in range(n): # <<<<<<<<<<<<<< * for j in range(n): * D[i,j] = -0.5*(D[i,j] - row_sum_view[i] - col_sum_view[j] + total) */ __pyx_t_7 = __pyx_v_n; __pyx_t_8 = __pyx_t_7; for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_i = __pyx_t_9; /* "mds_cython.pyx":123 * total /= (n*n) * for i in range(n): * for j in range(n): # <<<<<<<<<<<<<< * D[i,j] = -0.5*(D[i,j] - row_sum_view[i] - col_sum_view[j] + total) * */ __pyx_t_10 = __pyx_v_n; __pyx_t_11 = __pyx_t_10; for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { __pyx_v_j = __pyx_t_12; /* "mds_cython.pyx":124 * for i in range(n): * for j in range(n): * D[i,j] = -0.5*(D[i,j] - row_sum_view[i] - col_sum_view[j] + total) # <<<<<<<<<<<<<< * * */ __pyx_t_14 = __pyx_v_i; __pyx_t_13 = __pyx_v_j; __pyx_t_15 = __pyx_v_i; __pyx_t_16 = __pyx_v_j; __pyx_t_17 = __pyx_v_i; __pyx_t_18 = __pyx_v_j; *((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_17)) ) + __pyx_t_18 * __pyx_v_D.strides[1]) )) = (-0.5 * ((((*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_14)) ) + __pyx_t_13 * __pyx_v_D.strides[1]) ))) - (*((double *) ( /* dim=0 */ (__pyx_v_row_sum_view.data + __pyx_t_15 * __pyx_v_row_sum_view.strides[0]) )))) - (*((double *) ( /* dim=0 */ (__pyx_v_col_sum_view.data + __pyx_t_16 * __pyx_v_col_sum_view.strides[0]) )))) + __pyx_v_total)); } } /* "mds_cython.pyx":103 * @cython.wraparound(False) * @cython.cdivision(True) * cdef double_center(double[::1, :] D, int n): # <<<<<<<<<<<<<< * cdef int i, j * cdef double total = 0.0 */ /* 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_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __PYX_XDEC_MEMVIEW(&__pyx_t_6, 1); __Pyx_AddTraceback("mds_cython.double_center", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_row_sum_view, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_col_sum_view, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":131 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef cython_cmds_fortran_inplace(double[::1, :] D, int d, int n, double[::1, :] Y, int offset): # <<<<<<<<<<<<<< * double_center(D, n) # double-center first (n x n submatrix of D) * cdef double[:] W = np.empty(n, dtype=FLOAT64) */ static PyObject *__pyx_pw_10mds_cython_7cython_cmds_fortran_inplace(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_10mds_cython_cython_cmds_fortran_inplace(__Pyx_memviewslice __pyx_v_D, int __pyx_v_d, int __pyx_v_n, __Pyx_memviewslice __pyx_v_Y, int __pyx_v_offset, CYTHON_UNUSED int __pyx_skip_dispatch) { __Pyx_memviewslice __pyx_v_W = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Z = { 0, 0, { 0 }, { 0 }, { 0 } }; double __pyx_v_c_eval; int __pyx_v_i; int __pyx_v_di; 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; __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_t_6 = NULL; __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; Py_ssize_t __pyx_t_11; int __pyx_t_12; int __pyx_t_13; int __pyx_t_14; int __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("cython_cmds_fortran_inplace", 0); /* "mds_cython.pyx":132 * @cython.wraparound(False) * cpdef cython_cmds_fortran_inplace(double[::1, :] D, int d, int n, double[::1, :] Y, int offset): * double_center(D, n) # double-center first (n x n submatrix of D) # <<<<<<<<<<<<<< * cdef double[:] W = np.empty(n, dtype=FLOAT64) * cdef double[::1,:] Z = np.zeros(shape=(n, d), dtype=FLOAT64, order='F') */ __pyx_t_1 = __pyx_f_10mds_cython_double_center(__pyx_v_D, __pyx_v_n); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 132, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":133 * cpdef cython_cmds_fortran_inplace(double[::1, :] D, int d, int n, double[::1, :] Y, int offset): * double_center(D, n) # double-center first (n x n submatrix of D) * cdef double[:] W = np.empty(n, dtype=FLOAT64) # <<<<<<<<<<<<<< * cdef double[::1,:] Z = np.zeros(shape=(n, d), dtype=FLOAT64, order='F') * cdef double c_eval = 0.0 */ __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_n); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_FLOAT64); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 133, __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_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_t_4, PyBUF_WRITABLE); if (unlikely(!__pyx_t_5.memview)) __PYX_ERR(0, 133, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_W = __pyx_t_5; __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; /* "mds_cython.pyx":134 * double_center(D, n) # double-center first (n x n submatrix of D) * cdef double[:] W = np.empty(n, dtype=FLOAT64) * cdef double[::1,:] Z = np.zeros(shape=(n, d), dtype=FLOAT64, order='F') # <<<<<<<<<<<<<< * cdef double c_eval = 0.0 * cdef int i, di */ __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_n); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_d); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_2); __pyx_t_3 = 0; __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_shape, __pyx_t_6) < 0) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_FLOAT64); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_6) < 0) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_order, __pyx_n_u_F) < 0) __PYX_ERR(0, 134, __pyx_L1_error) __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_empty_tuple, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_7 = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(__pyx_t_6, PyBUF_WRITABLE); if (unlikely(!__pyx_t_7.memview)) __PYX_ERR(0, 134, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_v_Z = __pyx_t_7; __pyx_t_7.memview = NULL; __pyx_t_7.data = NULL; /* "mds_cython.pyx":135 * cdef double[:] W = np.empty(n, dtype=FLOAT64) * cdef double[::1,:] Z = np.zeros(shape=(n, d), dtype=FLOAT64, order='F') * cdef double c_eval = 0.0 # <<<<<<<<<<<<<< * cdef int i, di * cython_dsyevr_inplace(D, n-d+1, n, 1e-8, n, W, Z) */ __pyx_v_c_eval = 0.0; /* "mds_cython.pyx":137 * cdef double c_eval = 0.0 * cdef int i, di * cython_dsyevr_inplace(D, n-d+1, n, 1e-8, n, W, Z) # <<<<<<<<<<<<<< * for di in range(d): * if W[di] > 0: */ __pyx_t_6 = __Pyx_PyInt_From_long(((__pyx_v_n - __pyx_v_d) + 1)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_n); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = __pyx_f_10mds_cython_cython_dsyevr_inplace(__pyx_v_D, __pyx_t_6, __pyx_t_4, __pyx_float_1eneg_8, __pyx_v_n, __pyx_v_W, __pyx_v_Z, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":138 * cdef int i, di * cython_dsyevr_inplace(D, n-d+1, n, 1e-8, n, W, Z) * for di in range(d): # <<<<<<<<<<<<<< * if W[di] > 0: * c_eval = sqrt(W[di]) */ __pyx_t_8 = __pyx_v_d; __pyx_t_9 = __pyx_t_8; for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { __pyx_v_di = __pyx_t_10; /* "mds_cython.pyx":139 * cython_dsyevr_inplace(D, n-d+1, n, 1e-8, n, W, Z) * for di in range(d): * if W[di] > 0: # <<<<<<<<<<<<<< * c_eval = sqrt(W[di]) * for i in range(n): */ __pyx_t_11 = __pyx_v_di; __pyx_t_12 = (((*((double *) ( /* dim=0 */ (__pyx_v_W.data + __pyx_t_11 * __pyx_v_W.strides[0]) ))) > 0.0) != 0); if (__pyx_t_12) { /* "mds_cython.pyx":140 * for di in range(d): * if W[di] > 0: * c_eval = sqrt(W[di]) # <<<<<<<<<<<<<< * for i in range(n): * Y[di, offset+i] = c_eval*Z[i,di] */ __pyx_t_11 = __pyx_v_di; __pyx_v_c_eval = sqrt((*((double *) ( /* dim=0 */ (__pyx_v_W.data + __pyx_t_11 * __pyx_v_W.strides[0]) )))); /* "mds_cython.pyx":141 * if W[di] > 0: * c_eval = sqrt(W[di]) * for i in range(n): # <<<<<<<<<<<<<< * Y[di, offset+i] = c_eval*Z[i,di] * */ __pyx_t_13 = __pyx_v_n; __pyx_t_14 = __pyx_t_13; for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { __pyx_v_i = __pyx_t_15; /* "mds_cython.pyx":142 * c_eval = sqrt(W[di]) * for i in range(n): * Y[di, offset+i] = c_eval*Z[i,di] # <<<<<<<<<<<<<< * * */ __pyx_t_11 = __pyx_v_i; __pyx_t_16 = __pyx_v_di; __pyx_t_17 = __pyx_v_di; __pyx_t_18 = (__pyx_v_offset + __pyx_v_i); *((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_Y.data) + __pyx_t_17)) ) + __pyx_t_18 * __pyx_v_Y.strides[1]) )) = (__pyx_v_c_eval * (*((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_Z.data) + __pyx_t_11)) ) + __pyx_t_16 * __pyx_v_Z.strides[1]) )))); } /* "mds_cython.pyx":139 * cython_dsyevr_inplace(D, n-d+1, n, 1e-8, n, W, Z) * for di in range(d): * if W[di] > 0: # <<<<<<<<<<<<<< * c_eval = sqrt(W[di]) * for i in range(n): */ } } /* "mds_cython.pyx":131 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef cython_cmds_fortran_inplace(double[::1, :] D, int d, int n, double[::1, :] Y, int offset): # <<<<<<<<<<<<<< * double_center(D, n) # double-center first (n x n submatrix of D) * cdef double[:] W = np.empty(n, dtype=FLOAT64) */ /* 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_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __PYX_XDEC_MEMVIEW(&__pyx_t_5, 1); __Pyx_XDECREF(__pyx_t_6); __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); __Pyx_AddTraceback("mds_cython.cython_cmds_fortran_inplace", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_W, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_Z, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_7cython_cmds_fortran_inplace(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_10mds_cython_7cython_cmds_fortran_inplace(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_d; int __pyx_v_n; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_offset; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("cython_cmds_fortran_inplace (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_D,&__pyx_n_s_d,&__pyx_n_s_n,&__pyx_n_s_Y,&__pyx_n_s_offset,0}; PyObject* values[5] = {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 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_fortran_inplace", 1, 5, 5, 1); __PYX_ERR(0, 131, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_n)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_fortran_inplace", 1, 5, 5, 2); __PYX_ERR(0, 131, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_fortran_inplace", 1, 5, 5, 3); __PYX_ERR(0, 131, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_offset)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_fortran_inplace", 1, 5, 5, 4); __PYX_ERR(0, 131, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cython_cmds_fortran_inplace") < 0)) __PYX_ERR(0, 131, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { 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); } __pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_D.memview)) __PYX_ERR(0, 131, __pyx_L3_error) __pyx_v_d = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_d == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 131, __pyx_L3_error) __pyx_v_n = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_n == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 131, __pyx_L3_error) __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 131, __pyx_L3_error) __pyx_v_offset = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_offset == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 131, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("cython_cmds_fortran_inplace", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 131, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("mds_cython.cython_cmds_fortran_inplace", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10mds_cython_6cython_cmds_fortran_inplace(__pyx_self, __pyx_v_D, __pyx_v_d, __pyx_v_n, __pyx_v_Y, __pyx_v_offset); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython_6cython_cmds_fortran_inplace(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_D, int __pyx_v_d, int __pyx_v_n, __Pyx_memviewslice __pyx_v_Y, int __pyx_v_offset) { 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("cython_cmds_fortran_inplace", 0); __Pyx_XDECREF(__pyx_r); if (unlikely(!__pyx_v_D.memview)) { __Pyx_RaiseUnboundLocalError("D"); __PYX_ERR(0, 131, __pyx_L1_error) } if (unlikely(!__pyx_v_Y.memview)) { __Pyx_RaiseUnboundLocalError("Y"); __PYX_ERR(0, 131, __pyx_L1_error) } __pyx_t_1 = __pyx_f_10mds_cython_cython_cmds_fortran_inplace(__pyx_v_D, __pyx_v_d, __pyx_v_n, __pyx_v_Y, __pyx_v_offset, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 131, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("mds_cython.cython_cmds_fortran_inplace", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_D, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_Y, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":208 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef dist_matrix_subset(const double[::1, :] X, const int[:] ind, double[::1, :] D): # <<<<<<<<<<<<<< * ''' * Computes squared euclidean distance matrix of the points given by X[ind,:], */ static PyObject *__pyx_pw_10mds_cython_9dist_matrix_subset(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_10mds_cython_dist_matrix_subset(__Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_ind, __Pyx_memviewslice __pyx_v_D, CYTHON_UNUSED int __pyx_skip_dispatch) { Py_ssize_t __pyx_v_n; Py_ssize_t __pyx_v_d; Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_j; Py_ssize_t __pyx_v_k; double __pyx_v_tmp; double __pyx_v_diff; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __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; Py_ssize_t __pyx_t_10; Py_ssize_t __pyx_t_11; Py_ssize_t __pyx_t_12; Py_ssize_t __pyx_t_13; Py_ssize_t __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("dist_matrix_subset", 0); /* "mds_cython.pyx":213 * storing the results in the first (n x n) submatrix of D * ''' * cdef Py_ssize_t n = ind.size # <<<<<<<<<<<<<< * cdef Py_ssize_t d = X.shape[1] * cdef Py_ssize_t i, j, k */ __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_ind, 1, (PyObject *(*)(char *)) __pyx_memview_get_int__const__, (int (*)(char *, PyObject *)) NULL, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 213, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_size); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 213, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_3 = __Pyx_PyIndex_AsSsize_t(__pyx_t_2); if (unlikely((__pyx_t_3 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 213, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_n = __pyx_t_3; /* "mds_cython.pyx":214 * ''' * cdef Py_ssize_t n = ind.size * cdef Py_ssize_t d = X.shape[1] # <<<<<<<<<<<<<< * cdef Py_ssize_t i, j, k * cdef double tmp, diff */ __pyx_v_d = (__pyx_v_X.shape[1]); /* "mds_cython.pyx":217 * cdef Py_ssize_t i, j, k * cdef double tmp, diff * for i in prange(n, nogil=True, schedule='guided'): # <<<<<<<<<<<<<< * for j in range(i+1,n): * tmp = 0.0 */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { __pyx_t_3 = __pyx_v_n; if ((1 == 0)) abort(); { #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_5 = (__pyx_t_3 - 0 + 1 - 1/abs(1)) / 1; if (__pyx_t_5 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_10, __pyx_t_11, __pyx_t_12, __pyx_t_13, __pyx_t_14, __pyx_t_15, __pyx_t_16, __pyx_t_17, __pyx_t_6, __pyx_t_7, __pyx_t_8, __pyx_t_9) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_diff) firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) lastprivate(__pyx_v_j) lastprivate(__pyx_v_k) lastprivate(__pyx_v_tmp) schedule(guided) #endif /* _OPENMP */ for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_5; __pyx_t_4++){ { __pyx_v_i = (Py_ssize_t)(0 + 1 * __pyx_t_4); /* Initialize private variables to invalid values */ __pyx_v_diff = ((double)__PYX_NAN()); __pyx_v_j = ((Py_ssize_t)0xbad0bad0); __pyx_v_k = ((Py_ssize_t)0xbad0bad0); __pyx_v_tmp = ((double)__PYX_NAN()); /* "mds_cython.pyx":218 * cdef double tmp, diff * for i in prange(n, nogil=True, schedule='guided'): * for j in range(i+1,n): # <<<<<<<<<<<<<< * tmp = 0.0 * for k in range(d): */ __pyx_t_6 = __pyx_v_n; __pyx_t_7 = __pyx_t_6; for (__pyx_t_8 = (__pyx_v_i + 1); __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { __pyx_v_j = __pyx_t_8; /* "mds_cython.pyx":219 * for i in prange(n, nogil=True, schedule='guided'): * for j in range(i+1,n): * tmp = 0.0 # <<<<<<<<<<<<<< * for k in range(d): * diff = X[ind[i], k] - X[ind[j], k] */ __pyx_v_tmp = 0.0; /* "mds_cython.pyx":220 * for j in range(i+1,n): * tmp = 0.0 * for k in range(d): # <<<<<<<<<<<<<< * diff = X[ind[i], k] - X[ind[j], k] * tmp = tmp + (diff * diff) */ __pyx_t_9 = __pyx_v_d; __pyx_t_10 = __pyx_t_9; for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { __pyx_v_k = __pyx_t_11; /* "mds_cython.pyx":221 * tmp = 0.0 * for k in range(d): * diff = X[ind[i], k] - X[ind[j], k] # <<<<<<<<<<<<<< * tmp = tmp + (diff * diff) * D[i,j] = tmp */ __pyx_t_12 = __pyx_v_i; __pyx_t_13 = (*((int const *) ( /* dim=0 */ (__pyx_v_ind.data + __pyx_t_12 * __pyx_v_ind.strides[0]) ))); __pyx_t_14 = __pyx_v_k; __pyx_t_15 = __pyx_v_j; __pyx_t_16 = (*((int const *) ( /* dim=0 */ (__pyx_v_ind.data + __pyx_t_15 * __pyx_v_ind.strides[0]) ))); __pyx_t_17 = __pyx_v_k; __pyx_v_diff = ((*((double const *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double const *) __pyx_v_X.data) + __pyx_t_13)) ) + __pyx_t_14 * __pyx_v_X.strides[1]) ))) - (*((double const *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double const *) __pyx_v_X.data) + __pyx_t_16)) ) + __pyx_t_17 * __pyx_v_X.strides[1]) )))); /* "mds_cython.pyx":222 * for k in range(d): * diff = X[ind[i], k] - X[ind[j], k] * tmp = tmp + (diff * diff) # <<<<<<<<<<<<<< * D[i,j] = tmp * D[j,i] = tmp */ __pyx_v_tmp = (__pyx_v_tmp + (__pyx_v_diff * __pyx_v_diff)); } /* "mds_cython.pyx":223 * diff = X[ind[i], k] - X[ind[j], k] * tmp = tmp + (diff * diff) * D[i,j] = tmp # <<<<<<<<<<<<<< * D[j,i] = tmp * */ __pyx_t_15 = __pyx_v_i; __pyx_t_17 = __pyx_v_j; *((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_15)) ) + __pyx_t_17 * __pyx_v_D.strides[1]) )) = __pyx_v_tmp; /* "mds_cython.pyx":224 * tmp = tmp + (diff * diff) * D[i,j] = tmp * D[j,i] = tmp # <<<<<<<<<<<<<< * * # cdef np.ndarray[np.float64_t, ndim=2] D = np.zeros((n, n), np.double) */ __pyx_t_17 = __pyx_v_j; __pyx_t_15 = __pyx_v_i; *((double *) ( /* dim=1 */ (( /* dim=0 */ ((char *) (((double *) __pyx_v_D.data) + __pyx_t_17)) ) + __pyx_t_15 * __pyx_v_D.strides[1]) )) = __pyx_v_tmp; } } } } } } #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 } /* "mds_cython.pyx":217 * cdef Py_ssize_t i, j, k * cdef double tmp, diff * for i in prange(n, nogil=True, schedule='guided'): # <<<<<<<<<<<<<< * for j in range(i+1,n): * tmp = 0.0 */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "mds_cython.pyx":208 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef dist_matrix_subset(const double[::1, :] X, const int[:] ind, double[::1, :] D): # <<<<<<<<<<<<<< * ''' * Computes squared euclidean distance matrix of the points given by X[ind,:], */ /* 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_2); __Pyx_AddTraceback("mds_cython.dist_matrix_subset", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_9dist_matrix_subset(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10mds_cython_8dist_matrix_subset[] = " \n\tComputes squared euclidean distance matrix of the points given by X[ind,:], \n\tstoring the results in the first (n x n) submatrix of D \n\t"; static PyObject *__pyx_pw_10mds_cython_9dist_matrix_subset(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_ind = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("dist_matrix_subset (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_ind,&__pyx_n_s_D,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); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_ind)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("dist_matrix_subset", 1, 3, 3, 1); __PYX_ERR(0, 208, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("dist_matrix_subset", 1, 3, 3, 2); __PYX_ERR(0, 208, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "dist_matrix_subset") < 0)) __PYX_ERR(0, 208, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { 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); } __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dcd__double__const__(values[0], 0); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 208, __pyx_L3_error) __pyx_v_ind = __Pyx_PyObject_to_MemoryviewSlice_ds_int__const__(values[1], 0); if (unlikely(!__pyx_v_ind.memview)) __PYX_ERR(0, 208, __pyx_L3_error) __pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_D.memview)) __PYX_ERR(0, 208, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("dist_matrix_subset", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 208, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("mds_cython.dist_matrix_subset", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10mds_cython_8dist_matrix_subset(__pyx_self, __pyx_v_X, __pyx_v_ind, __pyx_v_D); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython_8dist_matrix_subset(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_ind, __Pyx_memviewslice __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("dist_matrix_subset", 0); __Pyx_XDECREF(__pyx_r); if (unlikely(!__pyx_v_X.memview)) { __Pyx_RaiseUnboundLocalError("X"); __PYX_ERR(0, 208, __pyx_L1_error) } if (unlikely(!__pyx_v_ind.memview)) { __Pyx_RaiseUnboundLocalError("ind"); __PYX_ERR(0, 208, __pyx_L1_error) } if (unlikely(!__pyx_v_D.memview)) { __Pyx_RaiseUnboundLocalError("D"); __PYX_ERR(0, 208, __pyx_L1_error) } __pyx_t_1 = __pyx_f_10mds_cython_dist_matrix_subset(__pyx_v_X, __pyx_v_ind, __pyx_v_D, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 208, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("mds_cython.dist_matrix_subset", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_ind, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_D, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":230 * @cython.boundscheck(False) * @cython.wraparound(False) * def cython_cmds_parallel(const double[::1, :] X, const int d, const int[:] ind_vec, const int[:] ind_len, const int max_n, double[::1, :] output): # <<<<<<<<<<<<<< * ''' * X := (d,n) matrix [columns-oriented (Fortran-style)] of points */ /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_11cython_cmds_parallel(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10mds_cython_10cython_cmds_parallel[] = " \n\t\tX := (d,n) matrix [columns-oriented (Fortran-style)] of points \n\t\tind_vec := (m,) contiguous vector of indices for each subset \n\t\tind_len := (j+1,) contiguous vector such that ind_vec[ind_len[i]:ind_len[i+1]] represents the i'th subset\n\t"; static PyMethodDef __pyx_mdef_10mds_cython_11cython_cmds_parallel = {"cython_cmds_parallel", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10mds_cython_11cython_cmds_parallel, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10mds_cython_10cython_cmds_parallel}; static PyObject *__pyx_pw_10mds_cython_11cython_cmds_parallel(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_d; __Pyx_memviewslice __pyx_v_ind_vec = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_ind_len = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_max_n; __Pyx_memviewslice __pyx_v_output = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("cython_cmds_parallel (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_d,&__pyx_n_s_ind_vec,&__pyx_n_s_ind_len,&__pyx_n_s_max_n,&__pyx_n_s_output,0}; PyObject* values[6] = {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 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); CYTHON_FALLTHROUGH; case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_d)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_parallel", 1, 6, 6, 1); __PYX_ERR(0, 230, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_ind_vec)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_parallel", 1, 6, 6, 2); __PYX_ERR(0, 230, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_ind_len)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_parallel", 1, 6, 6, 3); __PYX_ERR(0, 230, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_n)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_parallel", 1, 6, 6, 4); __PYX_ERR(0, 230, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 5: if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_output)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("cython_cmds_parallel", 1, 6, 6, 5); __PYX_ERR(0, 230, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "cython_cmds_parallel") < 0)) __PYX_ERR(0, 230, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { 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); } __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dcd__double__const__(values[0], 0); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 230, __pyx_L3_error) __pyx_v_d = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_d == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 230, __pyx_L3_error) __pyx_v_ind_vec = __Pyx_PyObject_to_MemoryviewSlice_ds_int__const__(values[2], 0); if (unlikely(!__pyx_v_ind_vec.memview)) __PYX_ERR(0, 230, __pyx_L3_error) __pyx_v_ind_len = __Pyx_PyObject_to_MemoryviewSlice_ds_int__const__(values[3], 0); if (unlikely(!__pyx_v_ind_len.memview)) __PYX_ERR(0, 230, __pyx_L3_error) __pyx_v_max_n = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_max_n == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 230, __pyx_L3_error) __pyx_v_output = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_output.memview)) __PYX_ERR(0, 230, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("cython_cmds_parallel", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 230, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("mds_cython.cython_cmds_parallel", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10mds_cython_10cython_cmds_parallel(__pyx_self, __pyx_v_X, __pyx_v_d, __pyx_v_ind_vec, __pyx_v_ind_len, __pyx_v_max_n, __pyx_v_output); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython_10cython_cmds_parallel(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, int __pyx_v_d, __Pyx_memviewslice __pyx_v_ind_vec, __Pyx_memviewslice __pyx_v_ind_len, int __pyx_v_max_n, __Pyx_memviewslice __pyx_v_output) { int __pyx_v_N; __Pyx_memviewslice __pyx_v_D_reuse = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_i; int __pyx_v_ni; int __pyx_v_nj; int __pyx_v_local_n; int __pyx_v_M; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations size_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; __Pyx_memviewslice __pyx_t_8 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; __Pyx_memviewslice __pyx_t_13 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_14; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("cython_cmds_parallel", 0); /* "mds_cython.pyx":236 * ind_len := (j+1,) contiguous vector such that ind_vec[ind_len[i]:ind_len[i+1]] represents the i'th subset * ''' * cdef int N = len(ind_vec) # <<<<<<<<<<<<<< * assert output.shape[0] == d and output.shape[1] == N * cdef double[::1, :] D_reuse = np.zeros((max_n,max_n), dtype='double', order='F') */ __pyx_t_1 = __Pyx_MemoryView_Len(__pyx_v_ind_vec); __pyx_v_N = __pyx_t_1; /* "mds_cython.pyx":237 * ''' * cdef int N = len(ind_vec) * assert output.shape[0] == d and output.shape[1] == N # <<<<<<<<<<<<<< * cdef double[::1, :] D_reuse = np.zeros((max_n,max_n), dtype='double', order='F') * cdef int i, ni, nj, local_n */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_3 = (((__pyx_v_output.shape[0]) == __pyx_v_d) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L3_bool_binop_done; } __pyx_t_3 = (((__pyx_v_output.shape[1]) == __pyx_v_N) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L3_bool_binop_done:; if (unlikely(!__pyx_t_2)) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 237, __pyx_L1_error) } } #endif /* "mds_cython.pyx":238 * cdef int N = len(ind_vec) * assert output.shape[0] == d and output.shape[1] == N * cdef double[::1, :] D_reuse = np.zeros((max_n,max_n), dtype='double', order='F') # <<<<<<<<<<<<<< * cdef int i, ni, nj, local_n * cdef int M = len(ind_len)-1 */ __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_max_n); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_max_n); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_6); __pyx_t_4 = 0; __pyx_t_6 = 0; __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_dtype, __pyx_n_u_double) < 0) __PYX_ERR(0, 238, __pyx_L1_error) if (PyDict_SetItem(__pyx_t_7, __pyx_n_s_order, __pyx_n_u_F) < 0) __PYX_ERR(0, 238, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_6, __pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_8 = __Pyx_PyObject_to_MemoryviewSlice_dcd__double(__pyx_t_4, PyBUF_WRITABLE); if (unlikely(!__pyx_t_8.memview)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_D_reuse = __pyx_t_8; __pyx_t_8.memview = NULL; __pyx_t_8.data = NULL; /* "mds_cython.pyx":240 * cdef double[::1, :] D_reuse = np.zeros((max_n,max_n), dtype='double', order='F') * cdef int i, ni, nj, local_n * cdef int M = len(ind_len)-1 # <<<<<<<<<<<<<< * for i in range(M): * ni = ind_len[i] */ __pyx_t_1 = __Pyx_MemoryView_Len(__pyx_v_ind_len); __pyx_v_M = (__pyx_t_1 - 1); /* "mds_cython.pyx":241 * cdef int i, ni, nj, local_n * cdef int M = len(ind_len)-1 * for i in range(M): # <<<<<<<<<<<<<< * ni = ind_len[i] * nj = ind_len[i+1] */ __pyx_t_9 = __pyx_v_M; __pyx_t_10 = __pyx_t_9; for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) { __pyx_v_i = __pyx_t_11; /* "mds_cython.pyx":242 * cdef int M = len(ind_len)-1 * for i in range(M): * ni = ind_len[i] # <<<<<<<<<<<<<< * nj = ind_len[i+1] * local_n = nj - ni */ __pyx_t_12 = __pyx_v_i; __pyx_v_ni = (*((int const *) ( /* dim=0 */ (__pyx_v_ind_len.data + __pyx_t_12 * __pyx_v_ind_len.strides[0]) ))); /* "mds_cython.pyx":243 * for i in range(M): * ni = ind_len[i] * nj = ind_len[i+1] # <<<<<<<<<<<<<< * local_n = nj - ni * dist_matrix_subset(X, ind_vec[ni:nj], D_reuse) */ __pyx_t_12 = (__pyx_v_i + 1); __pyx_v_nj = (*((int const *) ( /* dim=0 */ (__pyx_v_ind_len.data + __pyx_t_12 * __pyx_v_ind_len.strides[0]) ))); /* "mds_cython.pyx":244 * ni = ind_len[i] * nj = ind_len[i+1] * local_n = nj - ni # <<<<<<<<<<<<<< * dist_matrix_subset(X, ind_vec[ni:nj], D_reuse) * cython_cmds_fortran_inplace(D_reuse, d, local_n, output, ni) */ __pyx_v_local_n = (__pyx_v_nj - __pyx_v_ni); /* "mds_cython.pyx":245 * nj = ind_len[i+1] * local_n = nj - ni * dist_matrix_subset(X, ind_vec[ni:nj], D_reuse) # <<<<<<<<<<<<<< * cython_cmds_fortran_inplace(D_reuse, d, local_n, output, ni) * */ __pyx_t_13.data = __pyx_v_ind_vec.data; __pyx_t_13.memview = __pyx_v_ind_vec.memview; __PYX_INC_MEMVIEW(&__pyx_t_13, 0); __pyx_t_14 = -1; if (unlikely(__pyx_memoryview_slice_memviewslice( &__pyx_t_13, __pyx_v_ind_vec.shape[0], __pyx_v_ind_vec.strides[0], __pyx_v_ind_vec.suboffsets[0], 0, 0, &__pyx_t_14, __pyx_v_ni, __pyx_v_nj, 0, 1, 1, 0, 1) < 0)) { __PYX_ERR(0, 245, __pyx_L1_error) } __pyx_t_4 = __pyx_f_10mds_cython_dist_matrix_subset(__pyx_v_X, __pyx_t_13, __pyx_v_D_reuse, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 245, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __PYX_XDEC_MEMVIEW(&__pyx_t_13, 1); __pyx_t_13.memview = NULL; __pyx_t_13.data = NULL; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mds_cython.pyx":246 * local_n = nj - ni * dist_matrix_subset(X, ind_vec[ni:nj], D_reuse) * cython_cmds_fortran_inplace(D_reuse, d, local_n, output, ni) # <<<<<<<<<<<<<< * * */ __pyx_t_4 = __pyx_f_10mds_cython_cython_cmds_fortran_inplace(__pyx_v_D_reuse, __pyx_v_d, __pyx_v_local_n, __pyx_v_output, __pyx_v_ni, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 246, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } /* "mds_cython.pyx":230 * @cython.boundscheck(False) * @cython.wraparound(False) * def cython_cmds_parallel(const double[::1, :] X, const int d, const int[:] ind_vec, const int[:] ind_len, const int max_n, double[::1, :] output): # <<<<<<<<<<<<<< * ''' * X := (d,n) matrix [columns-oriented (Fortran-style)] of points */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __PYX_XDEC_MEMVIEW(&__pyx_t_8, 1); __PYX_XDEC_MEMVIEW(&__pyx_t_13, 1); __Pyx_AddTraceback("mds_cython.cython_cmds_parallel", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_D_reuse, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_X, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_ind_vec, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_ind_len, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_output, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mds_cython.pyx":250 * * import numpy as np * def flatten_list_of_lists(lst_of_lsts): # <<<<<<<<<<<<<< * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel */ /* Python wrapper */ static PyObject *__pyx_pw_10mds_cython_13flatten_list_of_lists(PyObject *__pyx_self, PyObject *__pyx_v_lst_of_lsts); /*proto*/ static PyMethodDef __pyx_mdef_10mds_cython_13flatten_list_of_lists = {"flatten_list_of_lists", (PyCFunction)__pyx_pw_10mds_cython_13flatten_list_of_lists, METH_O, 0}; static PyObject *__pyx_pw_10mds_cython_13flatten_list_of_lists(PyObject *__pyx_self, PyObject *__pyx_v_lst_of_lsts) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("flatten_list_of_lists (wrapper)", 0); __pyx_r = __pyx_pf_10mds_cython_12flatten_list_of_lists(__pyx_self, ((PyObject *)__pyx_v_lst_of_lsts)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10mds_cython_12flatten_list_of_lists(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_lst_of_lsts) { PyObject *__pyx_v_N = NULL; PyObject *__pyx_v_starts = NULL; PyObject *__pyx_v_values = NULL; PyObject *__pyx_v_cnt = NULL; PyObject *__pyx_v_i = NULL; PyObject *__pyx_v_lst = NULL; PyObject *__pyx_v_el = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; Py_ssize_t __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *(*__pyx_t_7)(PyObject *); Py_ssize_t __pyx_t_8; PyObject *(*__pyx_t_9)(PyObject *); int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("flatten_list_of_lists", 0); /* "mds_cython.pyx":251 * import numpy as np * def flatten_list_of_lists(lst_of_lsts): * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array # <<<<<<<<<<<<<< * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel * values = np.empty(N, dtype=np.int32) */ __pyx_t_1 = __Pyx_GetBuiltinName(__pyx_n_s_len); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_INCREF(__pyx_v_lst_of_lsts); __Pyx_GIVEREF(__pyx_v_lst_of_lsts); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_lst_of_lsts); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_map, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_sum, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_N = __pyx_t_2; __pyx_t_2 = 0; /* "mds_cython.pyx":252 * def flatten_list_of_lists(lst_of_lsts): * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel # <<<<<<<<<<<<<< * values = np.empty(N, dtype=np.int32) * starts[0], cnt = 0, 0 */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_3 = PyObject_Length(__pyx_v_lst_of_lsts); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(0, 252, __pyx_L1_error) __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_3 + 1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_int32); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_6) < 0) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_starts = __pyx_t_6; __pyx_t_6 = 0; /* "mds_cython.pyx":253 * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel * values = np.empty(N, dtype=np.int32) # <<<<<<<<<<<<<< * starts[0], cnt = 0, 0 * for i,lst in enumerate(lst_of_lsts): */ __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_np); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_INCREF(__pyx_v_N); __Pyx_GIVEREF(__pyx_v_N); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_v_N); __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_int32); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_5) < 0) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_values = __pyx_t_5; __pyx_t_5 = 0; /* "mds_cython.pyx":254 * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel * values = np.empty(N, dtype=np.int32) * starts[0], cnt = 0, 0 # <<<<<<<<<<<<<< * for i,lst in enumerate(lst_of_lsts): * for el in lst: */ __pyx_t_5 = __pyx_int_0; __Pyx_INCREF(__pyx_t_5); __pyx_t_4 = __pyx_int_0; __Pyx_INCREF(__pyx_t_4); if (unlikely(__Pyx_SetItemInt(__pyx_v_starts, 0, __pyx_t_5, long, 1, __Pyx_PyInt_From_long, 0, 0, 1) < 0)) __PYX_ERR(0, 254, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_cnt = __pyx_t_4; __pyx_t_4 = 0; /* "mds_cython.pyx":255 * values = np.empty(N, dtype=np.int32) * starts[0], cnt = 0, 0 * for i,lst in enumerate(lst_of_lsts): # <<<<<<<<<<<<<< * for el in lst: * values[cnt] = el */ __Pyx_INCREF(__pyx_int_0); __pyx_t_4 = __pyx_int_0; if (likely(PyList_CheckExact(__pyx_v_lst_of_lsts)) || PyTuple_CheckExact(__pyx_v_lst_of_lsts)) { __pyx_t_5 = __pyx_v_lst_of_lsts; __Pyx_INCREF(__pyx_t_5); __pyx_t_3 = 0; __pyx_t_7 = NULL; } else { __pyx_t_3 = -1; __pyx_t_5 = PyObject_GetIter(__pyx_v_lst_of_lsts); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_7 = Py_TYPE(__pyx_t_5)->tp_iternext; if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 255, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_7)) { if (likely(PyList_CheckExact(__pyx_t_5))) { if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_5)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_6 = PyList_GET_ITEM(__pyx_t_5, __pyx_t_3); __Pyx_INCREF(__pyx_t_6); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 255, __pyx_L1_error) #else __pyx_t_6 = PySequence_ITEM(__pyx_t_5, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_5)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_3); __Pyx_INCREF(__pyx_t_6); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 255, __pyx_L1_error) #else __pyx_t_6 = PySequence_ITEM(__pyx_t_5, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); #endif } } else { __pyx_t_6 = __pyx_t_7(__pyx_t_5); if (unlikely(!__pyx_t_6)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 255, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_6); } __Pyx_XDECREF_SET(__pyx_v_lst, __pyx_t_6); __pyx_t_6 = 0; __Pyx_INCREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_4); __pyx_t_6 = __Pyx_PyInt_AddObjC(__pyx_t_4, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = __pyx_t_6; __pyx_t_6 = 0; /* "mds_cython.pyx":256 * starts[0], cnt = 0, 0 * for i,lst in enumerate(lst_of_lsts): * for el in lst: # <<<<<<<<<<<<<< * values[cnt] = el * cnt += 1 # update index in the flattened array for the next element */ if (likely(PyList_CheckExact(__pyx_v_lst)) || PyTuple_CheckExact(__pyx_v_lst)) { __pyx_t_6 = __pyx_v_lst; __Pyx_INCREF(__pyx_t_6); __pyx_t_8 = 0; __pyx_t_9 = NULL; } else { __pyx_t_8 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_lst); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 256, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_9 = Py_TYPE(__pyx_t_6)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 256, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_9)) { if (likely(PyList_CheckExact(__pyx_t_6))) { if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_6)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_8); __Pyx_INCREF(__pyx_t_2); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 256, __pyx_L1_error) #else __pyx_t_2 = PySequence_ITEM(__pyx_t_6, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 256, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); #endif } else { if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_6)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_8); __Pyx_INCREF(__pyx_t_2); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 256, __pyx_L1_error) #else __pyx_t_2 = PySequence_ITEM(__pyx_t_6, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 256, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); #endif } } else { __pyx_t_2 = __pyx_t_9(__pyx_t_6); if (unlikely(!__pyx_t_2)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 256, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_2); } __Pyx_XDECREF_SET(__pyx_v_el, __pyx_t_2); __pyx_t_2 = 0; /* "mds_cython.pyx":257 * for i,lst in enumerate(lst_of_lsts): * for el in lst: * values[cnt] = el # <<<<<<<<<<<<<< * cnt += 1 # update index in the flattened array for the next element * starts[i+1] = cnt # remember the start of the next list */ if (unlikely(PyObject_SetItem(__pyx_v_values, __pyx_v_cnt, __pyx_v_el) < 0)) __PYX_ERR(0, 257, __pyx_L1_error) /* "mds_cython.pyx":258 * for el in lst: * values[cnt] = el * cnt += 1 # update index in the flattened array for the next element # <<<<<<<<<<<<<< * starts[i+1] = cnt # remember the start of the next list * return values, starts */ __pyx_t_2 = __Pyx_PyInt_AddObjC(__pyx_v_cnt, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF_SET(__pyx_v_cnt, __pyx_t_2); __pyx_t_2 = 0; /* "mds_cython.pyx":256 * starts[0], cnt = 0, 0 * for i,lst in enumerate(lst_of_lsts): * for el in lst: # <<<<<<<<<<<<<< * values[cnt] = el * cnt += 1 # update index in the flattened array for the next element */ } __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; /* "mds_cython.pyx":259 * values[cnt] = el * cnt += 1 # update index in the flattened array for the next element * starts[i+1] = cnt # remember the start of the next list # <<<<<<<<<<<<<< * return values, starts */ __pyx_t_6 = __Pyx_PyInt_AddObjC(__pyx_v_i, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (unlikely(PyObject_SetItem(__pyx_v_starts, __pyx_t_6, __pyx_v_cnt) < 0)) __PYX_ERR(0, 259, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; /* "mds_cython.pyx":255 * values = np.empty(N, dtype=np.int32) * starts[0], cnt = 0, 0 * for i,lst in enumerate(lst_of_lsts): # <<<<<<<<<<<<<< * for el in lst: * values[cnt] = el */ } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mds_cython.pyx":260 * cnt += 1 # update index in the flattened array for the next element * starts[i+1] = cnt # remember the start of the next list * return values, starts # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 260, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(__pyx_v_values); __Pyx_GIVEREF(__pyx_v_values); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_values); __Pyx_INCREF(__pyx_v_starts); __Pyx_GIVEREF(__pyx_v_starts); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_starts); __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; /* "mds_cython.pyx":250 * * import numpy as np * def flatten_list_of_lists(lst_of_lsts): # <<<<<<<<<<<<<< * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("mds_cython.flatten_list_of_lists", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_N); __Pyx_XDECREF(__pyx_v_starts); __Pyx_XDECREF(__pyx_v_values); __Pyx_XDECREF(__pyx_v_cnt); __Pyx_XDECREF(__pyx_v_i); __Pyx_XDECREF(__pyx_v_lst); __Pyx_XDECREF(__pyx_v_el); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cpython/array.pxd":93 * __data_union data * * def __getbuffer__(self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fulfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_7cpython_5array_5array_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_7cpython_5array_5array___getbuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags) { PyObject *__pyx_v_item_count = NULL; int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; char *__pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; Py_ssize_t __pyx_t_5; int __pyx_t_6; char __pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "cpython/array.pxd":98 * # In particular strided access is always provided regardless * # of flags * item_count = Py_SIZE(self) # <<<<<<<<<<<<<< * * info.suboffsets = NULL */ __pyx_t_1 = PyInt_FromSsize_t(Py_SIZE(((PyObject *)__pyx_v_self))); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 98, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_item_count = __pyx_t_1; __pyx_t_1 = 0; /* "cpython/array.pxd":100 * item_count = Py_SIZE(self) * * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.buf = self.data.as_chars * info.readonly = 0 */ __pyx_v_info->suboffsets = NULL; /* "cpython/array.pxd":101 * * info.suboffsets = NULL * info.buf = self.data.as_chars # <<<<<<<<<<<<<< * info.readonly = 0 * info.ndim = 1 */ __pyx_t_2 = __pyx_v_self->data.as_chars; __pyx_v_info->buf = __pyx_t_2; /* "cpython/array.pxd":102 * info.suboffsets = NULL * info.buf = self.data.as_chars * info.readonly = 0 # <<<<<<<<<<<<<< * info.ndim = 1 * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) */ __pyx_v_info->readonly = 0; /* "cpython/array.pxd":103 * info.buf = self.data.as_chars * info.readonly = 0 * info.ndim = 1 # <<<<<<<<<<<<<< * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) * info.len = info.itemsize * item_count */ __pyx_v_info->ndim = 1; /* "cpython/array.pxd":104 * info.readonly = 0 * info.ndim = 1 * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) # <<<<<<<<<<<<<< * info.len = info.itemsize * item_count * */ __pyx_t_3 = __pyx_v_self->ob_descr->itemsize; __pyx_v_info->itemsize = __pyx_t_3; /* "cpython/array.pxd":105 * info.ndim = 1 * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) * info.len = info.itemsize * item_count # <<<<<<<<<<<<<< * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) */ __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_info->itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 105, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_item_count); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 105, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_4); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 105, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_info->len = __pyx_t_5; /* "cpython/array.pxd":107 * info.len = info.itemsize * item_count * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) # <<<<<<<<<<<<<< * if not info.shape: * raise MemoryError() */ __pyx_v_info->shape = ((Py_ssize_t *)PyObject_Malloc(((sizeof(Py_ssize_t)) + 2))); /* "cpython/array.pxd":108 * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) * if not info.shape: # <<<<<<<<<<<<<< * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing */ __pyx_t_6 = ((!(__pyx_v_info->shape != 0)) != 0); if (unlikely(__pyx_t_6)) { /* "cpython/array.pxd":109 * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) * if not info.shape: * raise MemoryError() # <<<<<<<<<<<<<< * info.shape[0] = item_count # constant regardless of resizing * info.strides = &info.itemsize */ PyErr_NoMemory(); __PYX_ERR(1, 109, __pyx_L1_error) /* "cpython/array.pxd":108 * * info.shape = <Py_ssize_t*> PyObject_Malloc(sizeof(Py_ssize_t) + 2) * if not info.shape: # <<<<<<<<<<<<<< * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing */ } /* "cpython/array.pxd":110 * if not info.shape: * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing # <<<<<<<<<<<<<< * info.strides = &info.itemsize * */ __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_v_item_count); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 110, __pyx_L1_error) (__pyx_v_info->shape[0]) = __pyx_t_5; /* "cpython/array.pxd":111 * raise MemoryError() * info.shape[0] = item_count # constant regardless of resizing * info.strides = &info.itemsize # <<<<<<<<<<<<<< * * info.format = <char*> (info.shape + 1) */ __pyx_v_info->strides = (&__pyx_v_info->itemsize); /* "cpython/array.pxd":113 * info.strides = &info.itemsize * * info.format = <char*> (info.shape + 1) # <<<<<<<<<<<<<< * info.format[0] = self.ob_descr.typecode * info.format[1] = 0 */ __pyx_v_info->format = ((char *)(__pyx_v_info->shape + 1)); /* "cpython/array.pxd":114 * * info.format = <char*> (info.shape + 1) * info.format[0] = self.ob_descr.typecode # <<<<<<<<<<<<<< * info.format[1] = 0 * info.obj = self */ __pyx_t_7 = __pyx_v_self->ob_descr->typecode; (__pyx_v_info->format[0]) = __pyx_t_7; /* "cpython/array.pxd":115 * info.format = <char*> (info.shape + 1) * info.format[0] = self.ob_descr.typecode * info.format[1] = 0 # <<<<<<<<<<<<<< * info.obj = self * */ (__pyx_v_info->format[1]) = 0; /* "cpython/array.pxd":116 * info.format[0] = self.ob_descr.typecode * info.format[1] = 0 * info.obj = self # <<<<<<<<<<<<<< * * def __releasebuffer__(self, Py_buffer* info): */ __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); /* "cpython/array.pxd":93 * __data_union data * * def __getbuffer__(self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fulfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("cpython.array.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_XDECREF(__pyx_v_item_count); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cpython/array.pxd":118 * info.obj = self * * def __releasebuffer__(self, Py_buffer* info): # <<<<<<<<<<<<<< * PyObject_Free(info.shape) * */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_7cpython_5array_5array_2__releasebuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "cpython/array.pxd":119 * * def __releasebuffer__(self, Py_buffer* info): * PyObject_Free(info.shape) # <<<<<<<<<<<<<< * * array newarrayobject(PyTypeObject* type, Py_ssize_t size, arraydescr *descr) */ PyObject_Free(__pyx_v_info->shape); /* "cpython/array.pxd":118 * info.obj = self * * def __releasebuffer__(self, Py_buffer* info): # <<<<<<<<<<<<<< * PyObject_Free(info.shape) * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "cpython/array.pxd":130 * * * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< * """ fast creation of a new array, given a template array. * type will be same as template. */ static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *__pyx_v_template, Py_ssize_t __pyx_v_length, int __pyx_v_zero) { arrayobject *__pyx_v_op = 0; arrayobject *__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("clone", 0); /* "cpython/array.pxd":134 * type will be same as template. * if zero is true, new array will be initialized with zeroes.""" * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) # <<<<<<<<<<<<<< * if zero and op is not None: * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) */ __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_template)), __pyx_v_length, __pyx_v_template->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_op = ((arrayobject *)__pyx_t_1); __pyx_t_1 = 0; /* "cpython/array.pxd":135 * if zero is true, new array will be initialized with zeroes.""" * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) * if zero and op is not None: # <<<<<<<<<<<<<< * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) * return op */ __pyx_t_3 = (__pyx_v_zero != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = (((PyObject *)__pyx_v_op) != Py_None); __pyx_t_4 = (__pyx_t_3 != 0); __pyx_t_2 = __pyx_t_4; __pyx_L4_bool_binop_done:; if (__pyx_t_2) { /* "cpython/array.pxd":136 * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) * if zero and op is not None: * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) # <<<<<<<<<<<<<< * return op * */ (void)(memset(__pyx_v_op->data.as_chars, 0, (__pyx_v_length * __pyx_v_op->ob_descr->itemsize))); /* "cpython/array.pxd":135 * if zero is true, new array will be initialized with zeroes.""" * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) * if zero and op is not None: # <<<<<<<<<<<<<< * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) * return op */ } /* "cpython/array.pxd":137 * if zero and op is not None: * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) * return op # <<<<<<<<<<<<<< * * cdef inline array copy(array self): */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_op)); __pyx_r = __pyx_v_op; goto __pyx_L0; /* "cpython/array.pxd":130 * * * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< * """ fast creation of a new array, given a template array. * type will be same as template. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("cpython.array.clone", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_op); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cpython/array.pxd":139 * return op * * cdef inline array copy(array self): # <<<<<<<<<<<<<< * """ make a copy of an array. """ * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) */ static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_copy(arrayobject *__pyx_v_self) { arrayobject *__pyx_v_op = 0; arrayobject *__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("copy", 0); /* "cpython/array.pxd":141 * cdef inline array copy(array self): * """ make a copy of an array. """ * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) # <<<<<<<<<<<<<< * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) * return op */ __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_self)), Py_SIZE(((PyObject *)__pyx_v_self)), __pyx_v_self->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 141, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_op = ((arrayobject *)__pyx_t_1); __pyx_t_1 = 0; /* "cpython/array.pxd":142 * """ make a copy of an array. """ * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< * return op * */ (void)(memcpy(__pyx_v_op->data.as_chars, __pyx_v_self->data.as_chars, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize))); /* "cpython/array.pxd":143 * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) * return op # <<<<<<<<<<<<<< * * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_op)); __pyx_r = __pyx_v_op; goto __pyx_L0; /* "cpython/array.pxd":139 * return op * * cdef inline array copy(array self): # <<<<<<<<<<<<<< * """ make a copy of an array. """ * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("cpython.array.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_op); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cpython/array.pxd":145 * return op * * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< * """ efficient appending of new stuff of same type * (e.g. of same array type) */ static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *__pyx_v_self, char *__pyx_v_stuff, Py_ssize_t __pyx_v_n) { Py_ssize_t __pyx_v_itemsize; Py_ssize_t __pyx_v_origsize; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("extend_buffer", 0); /* "cpython/array.pxd":149 * (e.g. of same array type) * n: number of elements (not number of bytes!) """ * cdef Py_ssize_t itemsize = self.ob_descr.itemsize # <<<<<<<<<<<<<< * cdef Py_ssize_t origsize = Py_SIZE(self) * resize_smart(self, origsize + n) */ __pyx_t_1 = __pyx_v_self->ob_descr->itemsize; __pyx_v_itemsize = __pyx_t_1; /* "cpython/array.pxd":150 * n: number of elements (not number of bytes!) """ * cdef Py_ssize_t itemsize = self.ob_descr.itemsize * cdef Py_ssize_t origsize = Py_SIZE(self) # <<<<<<<<<<<<<< * resize_smart(self, origsize + n) * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) */ __pyx_v_origsize = Py_SIZE(((PyObject *)__pyx_v_self)); /* "cpython/array.pxd":151 * cdef Py_ssize_t itemsize = self.ob_descr.itemsize * cdef Py_ssize_t origsize = Py_SIZE(self) * resize_smart(self, origsize + n) # <<<<<<<<<<<<<< * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) * return 0 */ __pyx_t_1 = resize_smart(__pyx_v_self, (__pyx_v_origsize + __pyx_v_n)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 151, __pyx_L1_error) /* "cpython/array.pxd":152 * cdef Py_ssize_t origsize = Py_SIZE(self) * resize_smart(self, origsize + n) * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) # <<<<<<<<<<<<<< * return 0 * */ (void)(memcpy((__pyx_v_self->data.as_chars + (__pyx_v_origsize * __pyx_v_itemsize)), __pyx_v_stuff, (__pyx_v_n * __pyx_v_itemsize))); /* "cpython/array.pxd":153 * resize_smart(self, origsize + n) * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) * return 0 # <<<<<<<<<<<<<< * * cdef inline int extend(array self, array other) except -1: */ __pyx_r = 0; goto __pyx_L0; /* "cpython/array.pxd":145 * return op * * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< * """ efficient appending of new stuff of same type * (e.g. of same array type) */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("cpython.array.extend_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cpython/array.pxd":155 * return 0 * * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: */ static CYTHON_INLINE int __pyx_f_7cpython_5array_extend(arrayobject *__pyx_v_self, arrayobject *__pyx_v_other) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("extend", 0); /* "cpython/array.pxd":157 * cdef inline int extend(array self, array other) except -1: * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< * PyErr_BadArgument() * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) */ __pyx_t_1 = ((__pyx_v_self->ob_descr->typecode != __pyx_v_other->ob_descr->typecode) != 0); if (__pyx_t_1) { /* "cpython/array.pxd":158 * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: * PyErr_BadArgument() # <<<<<<<<<<<<<< * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * */ __pyx_t_2 = PyErr_BadArgument(); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 158, __pyx_L1_error) /* "cpython/array.pxd":157 * cdef inline int extend(array self, array other) except -1: * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< * PyErr_BadArgument() * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) */ } /* "cpython/array.pxd":159 * if self.ob_descr.typecode != other.ob_descr.typecode: * PyErr_BadArgument() * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) # <<<<<<<<<<<<<< * * cdef inline void zero(array self): */ __pyx_t_2 = __pyx_f_7cpython_5array_extend_buffer(__pyx_v_self, __pyx_v_other->data.as_chars, Py_SIZE(((PyObject *)__pyx_v_other))); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(1, 159, __pyx_L1_error) __pyx_r = __pyx_t_2; goto __pyx_L0; /* "cpython/array.pxd":155 * return 0 * * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< * """ extend array with data from another array; types must match. """ * if self.ob_descr.typecode != other.ob_descr.typecode: */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("cpython.array.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cpython/array.pxd":161 * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * * cdef inline void zero(array self): # <<<<<<<<<<<<<< * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) */ static CYTHON_INLINE void __pyx_f_7cpython_5array_zero(arrayobject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("zero", 0); /* "cpython/array.pxd":163 * cdef inline void zero(array self): * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) # <<<<<<<<<<<<<< */ (void)(memset(__pyx_v_self->data.as_chars, 0, (Py_SIZE(((PyObject *)__pyx_v_self)) * __pyx_v_self->ob_descr->itemsize))); /* "cpython/array.pxd":161 * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) * * cdef inline void zero(array self): # <<<<<<<<<<<<<< * """ set all elements of array to zero. """ * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":735 * 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); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":736 * * 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_ERR(2, 736, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":735 * 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; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":738 * 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); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":739 * * 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_ERR(2, 739, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":738 * 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; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":741 * 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); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":742 * * 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_ERR(2, 742, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":741 * 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; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":744 * 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); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":745 * * 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_ERR(2, 745, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":744 * 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; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":747 * 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); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":748 * * 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 tuple PyDataType_SHAPE(dtype d): */ __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_ERR(2, 748, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":747 * 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; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":750 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":751 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); if (__pyx_t_1) { /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":752 * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape # <<<<<<<<<<<<<< * else: * return () */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":751 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":754 * return <tuple>d.subarray.shape * else: * return () # <<<<<<<<<<<<<< * * */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_empty_tuple); __pyx_r = __pyx_empty_tuple; goto __pyx_L0; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":750 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":931 * int _import_umath() except -1 * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":932 * * cdef inline void set_array_base(ndarray arr, object base): * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<< * PyArray_SetBaseObject(arr, base) * */ Py_INCREF(__pyx_v_base); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":933 * cdef inline void set_array_base(ndarray arr, object base): * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base)); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":931 * int _import_umath() except -1 * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":935 * PyArray_SetBaseObject(arr, base) * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * base = PyArray_BASE(arr) * if base is NULL: */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_v_base; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":936 * * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) # <<<<<<<<<<<<<< * if base is NULL: * return None */ __pyx_v_base = PyArray_BASE(__pyx_v_arr); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":937 * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) * if base is NULL: # <<<<<<<<<<<<<< * return None * return <object>base */ __pyx_t_1 = ((__pyx_v_base == NULL) != 0); if (__pyx_t_1) { /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":938 * base = PyArray_BASE(arr) * if base is NULL: * return None # <<<<<<<<<<<<<< * return <object>base * */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":937 * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) * if base is NULL: # <<<<<<<<<<<<<< * return None * return <object>base */ } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":939 * if base is NULL: * return None * return <object>base # <<<<<<<<<<<<<< * * # Versions of the import_* functions which are more suitable for */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_base)); __pyx_r = ((PyObject *)__pyx_v_base); goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":935 * PyArray_SetBaseObject(arr, base) * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * base = PyArray_BASE(arr) * if base is NULL: */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":943 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * __pyx_import_array() */ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("import_array", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":944 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * __pyx_import_array() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":945 * cdef inline int import_array() except -1: * try: * __pyx_import_array() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.multiarray failed to import") */ __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 945, __pyx_L3_error) /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":944 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * __pyx_import_array() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":946 * try: * __pyx_import_array() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.multiarray failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(2, 946, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":947 * __pyx_import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 947, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(2, 947, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":944 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * __pyx_import_array() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":943 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * __pyx_import_array() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":949 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("import_umath", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":950 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":951 * cdef inline int import_umath() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 951, __pyx_L3_error) /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":950 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":952 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(2, 952, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":953 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 953, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(2, 953, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":950 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":949 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":955 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("import_ufunc", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":956 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":957 * cdef inline int import_ufunc() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 957, __pyx_L3_error) /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":956 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":958 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(2, 958, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":959 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef extern from *: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 959, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(2, 959, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":956 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":955 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":969 * * * cdef inline bint is_timedelta64_object(object obj): # <<<<<<<<<<<<<< * """ * Cython equivalent of `isinstance(obj, np.timedelta64)` */ static CYTHON_INLINE int __pyx_f_5numpy_is_timedelta64_object(PyObject *__pyx_v_obj) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_timedelta64_object", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":981 * bool * """ * return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) # <<<<<<<<<<<<<< * * */ __pyx_r = PyObject_TypeCheck(__pyx_v_obj, (&PyTimedeltaArrType_Type)); goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":969 * * * cdef inline bint is_timedelta64_object(object obj): # <<<<<<<<<<<<<< * """ * Cython equivalent of `isinstance(obj, np.timedelta64)` */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":984 * * * cdef inline bint is_datetime64_object(object obj): # <<<<<<<<<<<<<< * """ * Cython equivalent of `isinstance(obj, np.datetime64)` */ static CYTHON_INLINE int __pyx_f_5numpy_is_datetime64_object(PyObject *__pyx_v_obj) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_datetime64_object", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":996 * bool * """ * return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) # <<<<<<<<<<<<<< * * */ __pyx_r = PyObject_TypeCheck(__pyx_v_obj, (&PyDatetimeArrType_Type)); goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":984 * * * cdef inline bint is_datetime64_object(object obj): # <<<<<<<<<<<<<< * """ * Cython equivalent of `isinstance(obj, np.datetime64)` */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":999 * * * cdef inline npy_datetime get_datetime64_value(object obj) nogil: # <<<<<<<<<<<<<< * """ * returns the int64 value underlying scalar numpy datetime64 object */ static CYTHON_INLINE npy_datetime __pyx_f_5numpy_get_datetime64_value(PyObject *__pyx_v_obj) { npy_datetime __pyx_r; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1006 * also needed. That can be found using `get_datetime64_unit`. * """ * return (<PyDatetimeScalarObject*>obj).obval # <<<<<<<<<<<<<< * * */ __pyx_r = ((PyDatetimeScalarObject *)__pyx_v_obj)->obval; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":999 * * * cdef inline npy_datetime get_datetime64_value(object obj) nogil: # <<<<<<<<<<<<<< * """ * returns the int64 value underlying scalar numpy datetime64 object */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1009 * * * cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: # <<<<<<<<<<<<<< * """ * returns the int64 value underlying scalar numpy timedelta64 object */ static CYTHON_INLINE npy_timedelta __pyx_f_5numpy_get_timedelta64_value(PyObject *__pyx_v_obj) { npy_timedelta __pyx_r; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1013 * returns the int64 value underlying scalar numpy timedelta64 object * """ * return (<PyTimedeltaScalarObject*>obj).obval # <<<<<<<<<<<<<< * * */ __pyx_r = ((PyTimedeltaScalarObject *)__pyx_v_obj)->obval; goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1009 * * * cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: # <<<<<<<<<<<<<< * """ * returns the int64 value underlying scalar numpy timedelta64 object */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1016 * * * cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: # <<<<<<<<<<<<<< * """ * returns the unit part of the dtype for a numpy datetime64 object. */ static CYTHON_INLINE NPY_DATETIMEUNIT __pyx_f_5numpy_get_datetime64_unit(PyObject *__pyx_v_obj) { NPY_DATETIMEUNIT __pyx_r; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1020 * returns the unit part of the dtype for a numpy datetime64 object. * """ * return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base # <<<<<<<<<<<<<< */ __pyx_r = ((NPY_DATETIMEUNIT)((PyDatetimeScalarObject *)__pyx_v_obj)->obmeta.base); goto __pyx_L0; /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":1016 * * * cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: # <<<<<<<<<<<<<< * """ * returns the unit part of the dtype for a numpy datetime64 object. */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":122 * 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); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(3, 122, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(3, 122, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 4: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__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_ERR(3, 122, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; 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_ERR(3, 122, __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_ERR(3, 123, __pyx_L3_error) } else { /* "View.MemoryView":123 * * 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_ERR(3, 122, __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_ERR(3, 122, __pyx_L1_error) if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(3, 122, __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":122 * 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; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; int __pyx_t_8; Py_ssize_t __pyx_t_9; PyObject *__pyx_t_10 = NULL; Py_ssize_t __pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); /* "View.MemoryView":129 * 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_ERR(3, 129, __pyx_L1_error) } __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(3, 129, __pyx_L1_error) __pyx_v_self->ndim = ((int)__pyx_t_1); /* "View.MemoryView":130 * * self.ndim = <int> len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< * * if not self.ndim: */ __pyx_v_self->itemsize = __pyx_v_itemsize; /* "View.MemoryView":132 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":133 * * 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__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 133, __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_ERR(3, 133, __pyx_L1_error) /* "View.MemoryView":132 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ } /* "View.MemoryView":135 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":136 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 136, __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_ERR(3, 136, __pyx_L1_error) /* "View.MemoryView":135 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ } /* "View.MemoryView":138 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ __pyx_t_2 = PyBytes_Check(__pyx_v_format); __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":139 * * if not isinstance(format, bytes): * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 139, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); } } __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 139, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":138 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ } /* "View.MemoryView":140 * if not isinstance(format, bytes): * format = 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_ERR(3, 140, __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":141 * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ if (unlikely(__pyx_v_self->_format == Py_None)) { PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); __PYX_ERR(3, 141, __pyx_L1_error) } __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(3, 141, __pyx_L1_error) __pyx_v_self->format = __pyx_t_7; /* "View.MemoryView":144 * * * self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< * self._strides = self._shape + self.ndim * */ __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); /* "View.MemoryView":145 * * self._shape = <Py_ssize_t *> PyObject_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":147 * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":148 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 148, __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_ERR(3, 148, __pyx_L1_error) /* "View.MemoryView":147 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ } /* "View.MemoryView":151 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ __pyx_t_8 = 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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(3, 151, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(3, 151, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_dim = __pyx_t_9; __pyx_v_idx = __pyx_t_8; __pyx_t_8 = (__pyx_t_8 + 1); /* "View.MemoryView":152 * * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":153 * 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_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(3, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(3, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(3, 153, __pyx_L1_error) /* "View.MemoryView":152 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ } /* "View.MemoryView":154 * 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":151 * * * 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":157 * * 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_ERR(3, 157, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":158 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< * self.mode = u'fortran' * elif mode == 'c': */ __pyx_v_order = 'F'; /* "View.MemoryView":159 * 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; /* "View.MemoryView":157 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ goto __pyx_L10; } /* "View.MemoryView":160 * 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_ERR(3, 160, __pyx_L1_error) if (likely(__pyx_t_4)) { /* "View.MemoryView":161 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< * self.mode = u'c' * else: */ __pyx_v_order = 'C'; /* "View.MemoryView":162 * 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; /* "View.MemoryView":160 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ goto __pyx_L10; } /* "View.MemoryView":164 * 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, */ /*else*/ { __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 164, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(3, 164, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(3, 164, __pyx_L1_error) } __pyx_L10:; /* "View.MemoryView":166 * 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":169 * 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":170 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(3, 170, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 170, __pyx_L1_error) __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; /* "View.MemoryView":171 * 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":174 * * * 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":175 * * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":176 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(3, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(3, 176, __pyx_L1_error) /* "View.MemoryView":175 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ } /* "View.MemoryView":178 * 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":179 * * 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":180 * 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)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(3, 180, __pyx_L1_error) } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(3, 180, __pyx_L1_error) } __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); __pyx_t_9 = __pyx_t_1; for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { __pyx_v_i = __pyx_t_11; /* "View.MemoryView":181 * 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":182 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * @cname('getbuffer') */ Py_INCREF(Py_None); } /* "View.MemoryView":178 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ } /* "View.MemoryView":171 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":122 * 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_5); __Pyx_XDECREF(__pyx_t_6); __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":185 * * @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; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "View.MemoryView":186 * @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":187 * 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_ERR(3, 187, __pyx_L1_error) __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":188 * 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); /* "View.MemoryView":187 * 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": */ goto __pyx_L3; } /* "View.MemoryView":189 * 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_ERR(3, 189, __pyx_L1_error) __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":190 * 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); /* "View.MemoryView":189 * 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_L3:; /* "View.MemoryView":191 * 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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":192 * 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__7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 192, __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_ERR(3, 192, __pyx_L1_error) /* "View.MemoryView":191 * 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 */ } /* "View.MemoryView":193 * 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":194 * 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":195 * 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":196 * 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":197 * 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":198 * 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":199 * 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":200 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->readonly = 0; /* "View.MemoryView":202 * 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":203 * * 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; /* "View.MemoryView":202 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ goto __pyx_L5; } /* "View.MemoryView":205 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L5:; /* "View.MemoryView":207 * 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":185 * * @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->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":211 * __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":212 * * 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":213 * 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); /* "View.MemoryView":212 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ goto __pyx_L3; } /* "View.MemoryView":214 * 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":215 * 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":216 * 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); /* "View.MemoryView":215 * 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) */ } /* "View.MemoryView":218 * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) * free(self.data) # <<<<<<<<<<<<<< * PyObject_Free(self._shape) * */ free(__pyx_v_self->data); /* "View.MemoryView":214 * 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_L3:; /* "View.MemoryView":219 * self._strides, self.ndim, False) * free(self.data) * PyObject_Free(self._shape) # <<<<<<<<<<<<<< * * @property */ PyObject_Free(__pyx_v_self->_shape); /* "View.MemoryView":211 * __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":222 * * @property * def memview(self): # <<<<<<<<<<<<<< * return self.get_memview() * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(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) { 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":223 * @property * def memview(self): * return self.get_memview() # <<<<<<<<<<<<<< * * @cname('get_memview') */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 223, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":222 * * @property * def memview(self): # <<<<<<<<<<<<<< * return self.get_memview() * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __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":226 * * @cname('get_memview') * cdef get_memview(self): # <<<<<<<<<<<<<< * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) */ static PyObject *__pyx_array_get_memview(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_memview", 0); /* "View.MemoryView":227 * @cname('get_memview') * cdef get_memview(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":228 * cdef get_memview(self): * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * * def __len__(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 228, __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_ERR(3, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 228, __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":226 * * @cname('get_memview') * cdef get_memview(self): # <<<<<<<<<<<<<< * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) */ /* 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.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":230 * return memoryview(self, flags, self.dtype_is_object) * * def __len__(self): # <<<<<<<<<<<<<< * return self._shape[0] * */ /* Python wrapper */ static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__", 0); /* "View.MemoryView":231 * * def __len__(self): * return self._shape[0] # <<<<<<<<<<<<<< * * def __getattr__(self, attr): */ __pyx_r = (__pyx_v_self->_shape[0]); goto __pyx_L0; /* "View.MemoryView":230 * return memoryview(self, flags, self.dtype_is_object) * * def __len__(self): # <<<<<<<<<<<<<< * return self._shape[0] * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":233 * return self._shape[0] * * 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_8__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_8__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":234 * * 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_ERR(3, 234, __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_ERR(3, 234, __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":233 * return self._shape[0] * * 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":236 * 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_10__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_10__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":237 * * 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_ERR(3, 237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 237, __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":236 * 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":239 * 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_12__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_12__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":240 * * 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_ERR(3, 240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(3, 240, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":239 * 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; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_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("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(3, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { 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("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(3, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":244 * * @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":248 * 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":249 * * 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_ERR(3, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 249, __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_ERR(3, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 249, __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; /* "View.MemoryView":248 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ goto __pyx_L3; } /* "View.MemoryView":251 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ /*else*/ { __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 251, __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_ERR(3, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; /* "View.MemoryView":252 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(3, 252, __pyx_L1_error) /* "View.MemoryView":251 * 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 *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 251, __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":253 * 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":255 * 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":244 * * @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":281 * 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); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__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_ERR(3, 281, __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_ERR(3, 281, __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":282 * 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":281 * 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":283 * 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":284 * 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":283 * 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; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * cdef tuple state * cdef object _dict */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_v_state = 0; PyObject *__pyx_v__dict = 0; int __pyx_v_use_setstate; 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; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":5 * cdef object _dict * cdef bint use_setstate * state = (self.name,) # <<<<<<<<<<<<<< * _dict = getattr(self, '__dict__', None) * if _dict is not None: */ __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_self->name); __Pyx_GIVEREF(__pyx_v_self->name); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); __pyx_v_state = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":6 * cdef bint use_setstate * state = (self.name,) * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< * if _dict is not None: * state += (_dict,) */ __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v__dict = __pyx_t_1; __pyx_t_1 = 0; /* "(tree fragment)":7 * state = (self.name,) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< * state += (_dict,) * use_setstate = True */ __pyx_t_2 = (__pyx_v__dict != Py_None); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { /* "(tree fragment)":8 * _dict = getattr(self, '__dict__', None) * if _dict is not None: * state += (_dict,) # <<<<<<<<<<<<<< * use_setstate = True * else: */ __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v__dict); __Pyx_GIVEREF(__pyx_v__dict); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); __pyx_t_4 = 0; /* "(tree fragment)":9 * if _dict is not None: * state += (_dict,) * use_setstate = True # <<<<<<<<<<<<<< * else: * use_setstate = self.name is not None */ __pyx_v_use_setstate = 1; /* "(tree fragment)":7 * state = (self.name,) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< * state += (_dict,) * use_setstate = True */ goto __pyx_L3; } /* "(tree fragment)":11 * use_setstate = True * else: * use_setstate = self.name is not None # <<<<<<<<<<<<<< * if use_setstate: * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state */ /*else*/ { __pyx_t_3 = (__pyx_v_self->name != Py_None); __pyx_v_use_setstate = __pyx_t_3; } __pyx_L3:; /* "(tree fragment)":12 * else: * use_setstate = self.name is not None * if use_setstate: # <<<<<<<<<<<<<< * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: */ __pyx_t_3 = (__pyx_v_use_setstate != 0); if (__pyx_t_3) { /* "(tree fragment)":13 * use_setstate = self.name is not None * if use_setstate: * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) */ __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_INCREF(__pyx_int_184977713); __Pyx_GIVEREF(__pyx_int_184977713); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); __Pyx_INCREF(__pyx_v_state); __Pyx_GIVEREF(__pyx_v_state); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); __pyx_t_4 = 0; __pyx_t_1 = 0; __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "(tree fragment)":12 * else: * use_setstate = self.name is not None * if use_setstate: # <<<<<<<<<<<<<< * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: */ } /* "(tree fragment)":15 * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_INCREF(__pyx_int_184977713); __Pyx_GIVEREF(__pyx_int_184977713); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); __Pyx_INCREF(__pyx_v_state); __Pyx_GIVEREF(__pyx_v_state); PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); __pyx_t_5 = 0; __pyx_t_1 = 0; __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * cdef tuple state * cdef object _dict */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_state); __Pyx_XDECREF(__pyx_v__dict); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":16 * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { 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("__setstate_cython__", 0); /* "(tree fragment)":17 * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< */ if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(3, 17, __pyx_L1_error) __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":16 * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /* 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.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":298 * * @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":300 * 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":304 * * with cython.cdivision(True): * offset = aligned_p % alignment # <<<<<<<<<<<<<< * * if offset > 0: */ __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); /* "View.MemoryView":306 * 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":307 * * 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)); /* "View.MemoryView":306 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ } /* "View.MemoryView":309 * aligned_p += alignment - offset * * return <void *> aligned_p # <<<<<<<<<<<<<< * * */ __pyx_r = ((void *)__pyx_v_aligned_p); goto __pyx_L0; /* "View.MemoryView":298 * * @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":345 * 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); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(3, 345, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__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_ERR(3, 345, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; 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_ERR(3, 345, __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_ERR(3, 345, __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_ERR(3, 345, __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; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); /* "View.MemoryView":346 * * 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":347 * 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":348 * 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 *)__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":349 * 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 == ((int)-1))) __PYX_ERR(3, 349, __pyx_L1_error) /* "View.MemoryView":350 * 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":351 * __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":352 * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * global __pyx_memoryview_thread_locks_used */ Py_INCREF(Py_None); /* "View.MemoryView":350 * 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) */ } /* "View.MemoryView":348 * 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: */ } /* "View.MemoryView":355 * * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 */ __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); if (__pyx_t_1) { /* "View.MemoryView":356 * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: */ __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); /* "View.MemoryView":357 * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< * if self.lock is NULL: * self.lock = PyThread_allocate_lock() */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); /* "View.MemoryView":355 * * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 */ } /* "View.MemoryView":358 * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: # <<<<<<<<<<<<<< * self.lock = PyThread_allocate_lock() * if self.lock is NULL: */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":359 * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< * if self.lock is NULL: * raise MemoryError */ __pyx_v_self->lock = PyThread_allocate_lock(); /* "View.MemoryView":360 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":361 * self.lock = PyThread_allocate_lock() * if self.lock is NULL: * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ PyErr_NoMemory(); __PYX_ERR(3, 361, __pyx_L1_error) /* "View.MemoryView":360 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ } /* "View.MemoryView":358 * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: # <<<<<<<<<<<<<< * self.lock = PyThread_allocate_lock() * if self.lock is NULL: */ } /* "View.MemoryView":363 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":364 * * if flags & PyBUF_FORMAT: * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< * else: * self.dtype_is_object = dtype_is_object */ __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L11_bool_binop_done; } __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); __pyx_t_1 = __pyx_t_2; __pyx_L11_bool_binop_done:; __pyx_v_self->dtype_is_object = __pyx_t_1; /* "View.MemoryView":363 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ goto __pyx_L10; } /* "View.MemoryView":366 * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( */ /*else*/ { __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; } __pyx_L10:; /* "View.MemoryView":368 * 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":370 * 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":345 * 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_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":372 * 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) { int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; PyThread_type_lock __pyx_t_6; PyThread_type_lock __pyx_t_7; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":373 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: */ __pyx_t_1 = (__pyx_v_self->obj != Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":374 * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< * elif (<__pyx_buffer *> &self.view).obj == Py_None: * */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); /* "View.MemoryView":373 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: */ goto __pyx_L3; } /* "View.MemoryView":375 * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< * * (<__pyx_buffer *> &self.view).obj = NULL */ __pyx_t_2 = ((((Py_buffer *)(&__pyx_v_self->view))->obj == Py_None) != 0); if (__pyx_t_2) { /* "View.MemoryView":377 * elif (<__pyx_buffer *> &self.view).obj == Py_None: * * (<__pyx_buffer *> &self.view).obj = NULL # <<<<<<<<<<<<<< * Py_DECREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_self->view))->obj = NULL; /* "View.MemoryView":378 * * (<__pyx_buffer *> &self.view).obj = NULL * Py_DECREF(Py_None) # <<<<<<<<<<<<<< * * cdef int i */ Py_DECREF(Py_None); /* "View.MemoryView":375 * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< * * (<__pyx_buffer *> &self.view).obj = NULL */ } __pyx_L3:; /* "View.MemoryView":382 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: */ __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":383 * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 */ __pyx_t_3 = __pyx_memoryview_thread_locks_used; __pyx_t_4 = __pyx_t_3; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":384 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: */ __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); if (__pyx_t_2) { /* "View.MemoryView":385 * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); /* "View.MemoryView":386 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); if (__pyx_t_2) { /* "View.MemoryView":388 * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< * break * else: */ __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); /* "View.MemoryView":387 * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) * break */ (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; /* "View.MemoryView":386 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ } /* "View.MemoryView":389 * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) * break # <<<<<<<<<<<<<< * else: * PyThread_free_lock(self.lock) */ goto __pyx_L6_break; /* "View.MemoryView":384 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: */ } } /*else*/ { /* "View.MemoryView":391 * break * else: * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< * * cdef char *get_item_pointer(memoryview self, object index) except NULL: */ PyThread_free_lock(__pyx_v_self->lock); } __pyx_L6_break:; /* "View.MemoryView":382 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: */ } /* "View.MemoryView":372 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":393 * 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":395 * 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":397 * 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_ERR(3, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 397, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 397, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 397, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #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(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(3, 397, __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":398 * * 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_ERR(3, 398, __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 == ((char *)NULL))) __PYX_ERR(3, 398, __pyx_L1_error) __pyx_v_itemp = __pyx_t_7; /* "View.MemoryView":397 * 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":400 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_itemp; goto __pyx_L0; /* "View.MemoryView":393 * 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":403 * * * 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":404 * * 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":405 * 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":404 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ } /* "View.MemoryView":407 * 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_ERR(3, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(3, 407, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(3, 407, __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":410 * * 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_ERR(3, 410, __pyx_L1_error) if (__pyx_t_2) { /* "View.MemoryView":411 * 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_ERR(3, 411, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":410 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ } /* "View.MemoryView":413 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< * return self.convert_item_to_object(itemp) * */ /*else*/ { __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 == ((char *)NULL))) __PYX_ERR(3, 413, __pyx_L1_error) __pyx_v_itemp = __pyx_t_6; /* "View.MemoryView":414 * 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_ERR(3, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":403 * * * 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":416 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") */ /* 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 int __pyx_t_1; 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; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); /* "View.MemoryView":417 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< * raise TypeError("Cannot assign to read-only memoryview") * */ __pyx_t_1 = (__pyx_v_self->view.readonly != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":418 * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< * * have_slices, index = _unellipsify(index, self.view.ndim) */ __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 418, __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_ERR(3, 418, __pyx_L1_error) /* "View.MemoryView":417 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< * raise TypeError("Cannot assign to read-only memoryview") * */ } /* "View.MemoryView":420 * raise TypeError("Cannot assign to read-only memoryview") * * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (likely(__pyx_t_2 != Py_None)) { PyObject* sequence = __pyx_t_2; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(3, 420, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(3, 420, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_3; __pyx_t_3 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":422 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(3, 422, __pyx_L1_error) if (__pyx_t_1) { /* "View.MemoryView":423 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 423, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_obj = __pyx_t_2; __pyx_t_2 = 0; /* "View.MemoryView":424 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(3, 424, __pyx_L1_error) if (__pyx_t_1) { /* "View.MemoryView":425 * 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_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 425, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 425, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":424 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ goto __pyx_L5; } /* "View.MemoryView":427 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< * else: * self.setitem_indexed(index, value) */ /*else*/ { __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 427, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(3, 427, __pyx_L1_error) __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 427, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L5:; /* "View.MemoryView":422 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ goto __pyx_L4; } /* "View.MemoryView":429 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ /*else*/ { __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 429, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L4:; /* "View.MemoryView":416 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __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":431 * 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":432 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __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":434 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":435 * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | 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_ERR(3, 435, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); /* "View.MemoryView":434 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 434, __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; /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ } __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_L9_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; /* "View.MemoryView":436 * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< * return None * */ __pyx_t_9 = __Pyx_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_ERR(3, 436, __pyx_L6_except_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":437 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< * * return obj */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(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:; /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ __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_L9_try_end:; } /* "View.MemoryView":432 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, */ } /* "View.MemoryView":439 * 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":431 * 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":441 * 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 __Pyx_memviewslice *__pyx_t_1; __Pyx_memviewslice *__pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; int __pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); /* "View.MemoryView":445 * 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_ERR(3, 445, __pyx_L1_error) __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(3, 445, __pyx_L1_error) /* "View.MemoryView":446 * * 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_ERR(3, 446, __pyx_L1_error) __pyx_t_2 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice)); if (unlikely(__pyx_t_2 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(3, 446, __pyx_L1_error) /* "View.MemoryView":447 * 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_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 447, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 447, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 447, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 447, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":445 * 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_6 = __pyx_memoryview_copy_contents((__pyx_t_1[0]), (__pyx_t_2[0]), __pyx_t_4, __pyx_t_5, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(3, 445, __pyx_L1_error) /* "View.MemoryView":441 * 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_3); __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":449 * 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[0x80]; 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 __Pyx_memviewslice *__pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; char const *__pyx_t_6; 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; PyObject *__pyx_t_12 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); /* "View.MemoryView":451 * 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":456 * 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_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(3, 456, __pyx_L1_error) __pyx_v_dst_slice = __pyx_t_1; /* "View.MemoryView":458 * 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_2 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); if (__pyx_t_2) { /* "View.MemoryView":459 * * 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":460 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ __pyx_t_2 = ((__pyx_v_tmp == NULL) != 0); if (unlikely(__pyx_t_2)) { /* "View.MemoryView":461 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ PyErr_NoMemory(); __PYX_ERR(3, 461, __pyx_L1_error) /* "View.MemoryView":460 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ } /* "View.MemoryView":462 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< * else: * item = <void *> array */ __pyx_v_item = __pyx_v_tmp; /* "View.MemoryView":458 * 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: */ goto __pyx_L3; } /* "View.MemoryView":464 * item = tmp * else: * item = <void *> array # <<<<<<<<<<<<<< * * try: */ /*else*/ { __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; /* "View.MemoryView":466 * item = <void *> array * * try: # <<<<<<<<<<<<<< * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value */ /*try:*/ { /* "View.MemoryView":467 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ __pyx_t_2 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_2) { /* "View.MemoryView":468 * 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); /* "View.MemoryView":467 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ goto __pyx_L8; } /* "View.MemoryView":470 * (<PyObject **> item)[0] = <PyObject *> value * else: * self.assign_item_from_object(<char *> item, value) # <<<<<<<<<<<<<< * * */ /*else*/ { __pyx_t_3 = ((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_3)) __PYX_ERR(3, 470, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L8:; /* "View.MemoryView":474 * * * 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_2 = ((__pyx_v_self->view.suboffsets != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":475 * * 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_3 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 475, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":474 * * * 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, */ } /* "View.MemoryView":476 * 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":479 * 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; } __pyx_L6_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); __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_XGOTREF(__pyx_t_12); __pyx_t_4 = __pyx_lineno; __pyx_t_5 = __pyx_clineno; __pyx_t_6 = __pyx_filename; { PyMem_Free(__pyx_v_tmp); } if (PY_MAJOR_VERSION >= 3) { __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_XGIVEREF(__pyx_t_12); __Pyx_ExceptionReset(__pyx_t_10, __pyx_t_11, __pyx_t_12); } __Pyx_XGIVEREF(__pyx_t_7); __Pyx_XGIVEREF(__pyx_t_8); __Pyx_XGIVEREF(__pyx_t_9); __Pyx_ErrRestore(__pyx_t_7, __pyx_t_8, __pyx_t_9); __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_5; __pyx_filename = __pyx_t_6; goto __pyx_L1_error; } __pyx_L7:; } /* "View.MemoryView":449 * 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_3); __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":481 * 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":482 * * 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 == ((char *)NULL))) __PYX_ERR(3, 482, __pyx_L1_error) __pyx_v_itemp = __pyx_t_1; /* "View.MemoryView":483 * 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_ERR(3, 483, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":481 * 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":485 * 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; int __pyx_t_8; PyObject *__pyx_t_9 = NULL; size_t __pyx_t_10; int __pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":488 * """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, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 488, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":491 * 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_ERR(3, 491, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __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":493 * 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_ERR(3, 493, __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_ERR(3, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && 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; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 493, __pyx_L3_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 493, __pyx_L3_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else #endif { __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_7) { __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; } __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); __Pyx_INCREF(__pyx_v_bytesitem); __Pyx_GIVEREF(__pyx_v_bytesitem); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __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_ERR(3, 493, __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; /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ } /* "View.MemoryView":497 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ /*else:*/ { __pyx_t_10 = strlen(__pyx_v_self->view.format); __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { /* "View.MemoryView":498 * 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)) __PYX_ERR(3, 498, __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":497 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ } /* "View.MemoryView":499 * 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_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; /* "View.MemoryView":494 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 494, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; if (__pyx_t_8) { __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(3, 494, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_1); /* "View.MemoryView":495 * 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__11, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 495, __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_ERR(3, 495, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.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":485 * 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":501 * 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; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; Py_ssize_t __pyx_t_9; PyObject *__pyx_t_10 = NULL; char *__pyx_t_11; char *__pyx_t_12; char *__pyx_t_13; char *__pyx_t_14; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":504 * """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, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 504, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":509 * 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":510 * * 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_ERR(3, 510, __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_ERR(3, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 510, __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_ERR(3, 510, __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_ERR(3, 510, __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_ERR(3, 510, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":509 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ goto __pyx_L3; } /* "View.MemoryView":512 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< * * for i, c in enumerate(bytesvalue): */ /*else*/ { __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 512, __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_ERR(3, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; if (CYTHON_UNPACK_METHODS && 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; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 512, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 512, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif { __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); if (__pyx_t_5) { __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; } __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_v_value); __Pyx_GIVEREF(__pyx_v_value); PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __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_ERR(3, 512, __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_ERR(3, 512, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; /* "View.MemoryView":514 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_9 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); __PYX_ERR(3, 514, __pyx_L1_error) } __Pyx_INCREF(__pyx_v_bytesvalue); __pyx_t_10 = __pyx_v_bytesvalue; __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { __pyx_t_11 = __pyx_t_14; __pyx_v_c = (__pyx_t_11[0]); /* "View.MemoryView":515 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ __pyx_v_i = __pyx_t_9; /* "View.MemoryView":514 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_9 = (__pyx_t_9 + 1); /* "View.MemoryView":515 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; } __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; /* "View.MemoryView":501 * 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_10); __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":518 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") */ /* 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; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; Py_ssize_t *__pyx_t_4; char *__pyx_t_5; void *__pyx_t_6; int __pyx_t_7; Py_ssize_t __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "View.MemoryView":519 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< * raise ValueError("Cannot create writable memory view from read-only memoryview") * */ __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L4_bool_binop_done; } __pyx_t_2 = (__pyx_v_self->view.readonly != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; if (unlikely(__pyx_t_1)) { /* "View.MemoryView":520 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< * * if flags & PyBUF_ND: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 520, __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_ERR(3, 520, __pyx_L1_error) /* "View.MemoryView":519 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< * raise ValueError("Cannot create writable memory view from read-only memoryview") * */ } /* "View.MemoryView":522 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); if (__pyx_t_1) { /* "View.MemoryView":523 * * if flags & PyBUF_ND: * info.shape = self.view.shape # <<<<<<<<<<<<<< * else: * info.shape = NULL */ __pyx_t_4 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_4; /* "View.MemoryView":522 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ goto __pyx_L6; } /* "View.MemoryView":525 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ /*else*/ { __pyx_v_info->shape = NULL; } __pyx_L6:; /* "View.MemoryView":527 * 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":528 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< * else: * info.strides = NULL */ __pyx_t_4 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_4; /* "View.MemoryView":527 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ goto __pyx_L7; } /* "View.MemoryView":530 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ /*else*/ { __pyx_v_info->strides = NULL; } __pyx_L7:; /* "View.MemoryView":532 * 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":533 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< * else: * info.suboffsets = NULL */ __pyx_t_4 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_4; /* "View.MemoryView":532 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ goto __pyx_L8; } /* "View.MemoryView":535 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ /*else*/ { __pyx_v_info->suboffsets = NULL; } __pyx_L8:; /* "View.MemoryView":537 * 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":538 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_5 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_5; /* "View.MemoryView":537 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ goto __pyx_L9; } /* "View.MemoryView":540 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L9:; /* "View.MemoryView":542 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize */ __pyx_t_6 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_6; /* "View.MemoryView":543 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< * info.itemsize = self.view.itemsize * info.len = self.view.len */ __pyx_t_7 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_7; /* "View.MemoryView":544 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< * info.len = self.view.len * info.readonly = self.view.readonly */ __pyx_t_8 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_8; /* "View.MemoryView":545 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< * info.readonly = self.view.readonly * info.obj = self */ __pyx_t_8 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_8; /* "View.MemoryView":546 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = self.view.readonly # <<<<<<<<<<<<<< * info.obj = self * */ __pyx_t_1 = __pyx_v_self->view.readonly; __pyx_v_info->readonly = __pyx_t_1; /* "View.MemoryView":547 * info.len = self.view.len * info.readonly = self.view.readonly * 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":518 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":553 * * @property * def T(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(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":554 * @property * def T(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_ERR(3, 554, __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_ERR(3, 554, __pyx_L1_error) __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":555 * def T(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 == ((int)0))) __PYX_ERR(3, 555, __pyx_L1_error) /* "View.MemoryView":556 * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) * return result # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":553 * * @property * def T(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":559 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(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":560 * @property * def base(self): * return self.obj # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->obj); __pyx_r = __pyx_v_self->obj; goto __pyx_L0; /* "View.MemoryView":559 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":563 * * @property * def shape(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(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":564 * @property * def shape(self): * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 564, __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_ERR(3, 564, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(3, 564, __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_ERR(3, 564, __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":563 * * @property * def shape(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":567 * * @property * def strides(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(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":568 * @property * def strides(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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":570 * 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__13, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 570, __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_ERR(3, 570, __pyx_L1_error) /* "View.MemoryView":568 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ } /* "View.MemoryView":572 * raise ValueError("Buffer view does not expose strides") * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 572, __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_ERR(3, 572, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(3, 572, __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_ERR(3, 572, __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":567 * * @property * def strides(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":575 * * @property * def suboffsets(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(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":576 * @property * def suboffsets(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":577 * def suboffsets(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_ERR(3, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__14, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 577, __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":576 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ } /* "View.MemoryView":579 * return (-1,) * self.view.ndim * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 579, __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_ERR(3, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(3, 579, __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_ERR(3, 579, __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":575 * * @property * def suboffsets(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":582 * * @property * def ndim(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(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":583 * @property * def ndim(self): * return self.view.ndim # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 583, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":582 * * @property * def ndim(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":586 * * @property * def itemsize(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(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":587 * @property * def itemsize(self): * return self.view.itemsize # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 587, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":586 * * @property * def itemsize(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":590 * * @property * def nbytes(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(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":591 * @property * def nbytes(self): * return self.size * self.view.itemsize # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 591, __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_ERR(3, 591, __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_ERR(3, 591, __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":590 * * @property * def nbytes(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":594 * * @property * def size(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(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":595 * @property * def size(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":596 * def size(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":598 * 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_ERR(3, 598, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; /* "View.MemoryView":599 * * 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_ERR(3, 599, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } /* "View.MemoryView":601 * 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; /* "View.MemoryView":595 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ } /* "View.MemoryView":603 * 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":594 * * @property * def size(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":605 * 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":606 * * 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":607 * 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":606 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ } /* "View.MemoryView":609 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< * * def __repr__(self): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":605 * 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":611 * 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":612 * * 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_ERR(3, 612, __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_ERR(3, 612, __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_ERR(3, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":613 * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 613, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); /* "View.MemoryView":612 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 612, __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":611 * 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":615 * 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":616 * * 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_ERR(3, 616, __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_ERR(3, 616, __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_ERR(3, 616, __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_ERR(3, 616, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __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_ERR(3, 616, __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":615 * 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":619 * * * 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 __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("is_c_contig", 0); /* "View.MemoryView":622 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice[0], 'C', self.view.ndim) * */ __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(3, 622, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":623 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< * * def is_f_contig(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 623, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":619 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __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":625 * return slice_is_contig(mslice[0], '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 __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("is_f_contig", 0); /* "View.MemoryView":628 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice[0], 'F', self.view.ndim) * */ __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(3, 628, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":629 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< * * def copy(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 629, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":625 * return slice_is_contig(mslice[0], '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_2); __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":631 * return slice_is_contig(mslice[0], '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":633 * 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":635 * 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":636 * * 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), ((char *)"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_ERR(3, 636, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":641 * 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_ERR(3, 641, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":631 * return slice_is_contig(mslice[0], '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":643 * 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":645 * 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":647 * 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":648 * * 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), ((char *)"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_ERR(3, 648, __pyx_L1_error) __pyx_v_dst = __pyx_t_1; /* "View.MemoryView":653 * 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_ERR(3, 653, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":643 * 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; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED 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("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(3, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { 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("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(3, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":657 * * @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":658 * @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_ERR(3, 658, __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_ERR(3, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 658, __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":659 * 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":660 * 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":657 * * @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":663 * * @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":664 * @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, __pyx_memoryview_type); __pyx_r = __pyx_t_1; goto __pyx_L0; /* "View.MemoryView":663 * * @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":666 * 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":671 * 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":672 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 672, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; /* "View.MemoryView":671 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ goto __pyx_L3; } /* "View.MemoryView":674 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ /*else*/ { __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; /* "View.MemoryView":676 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 676, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":677 * * result = [] * have_slices = False # <<<<<<<<<<<<<< * seen_ellipsis = False * for idx, item in enumerate(tup): */ __pyx_v_have_slices = 0; /* "View.MemoryView":678 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< * for idx, item in enumerate(tup): * if item is Ellipsis: */ __pyx_v_seen_ellipsis = 0; /* "View.MemoryView":679 * 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_ERR(3, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 679, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 679, __pyx_L1_error) #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 679, __pyx_L1_error) #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #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(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(3, 679, __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 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 679, __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":680 * 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":681 * 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":682 * 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 == ((Py_ssize_t)-1))) __PYX_ERR(3, 682, __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_ERR(3, 682, __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__17); __Pyx_GIVEREF(__pyx_slice__17); PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__17); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(3, 682, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":683 * 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; /* "View.MemoryView":681 * 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 */ goto __pyx_L7; } /* "View.MemoryView":685 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ /*else*/ { __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__17); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(3, 685, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":686 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< * else: * if not isinstance(item, slice) and not PyIndex_Check(item): */ __pyx_v_have_slices = 1; /* "View.MemoryView":680 * 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)) */ goto __pyx_L6; } /* "View.MemoryView":688 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ /*else*/ { __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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":689 * 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_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 689, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(3, 689, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_Raise(__pyx_t_11, 0, 0, 0); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __PYX_ERR(3, 689, __pyx_L1_error) /* "View.MemoryView":688 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ } /* "View.MemoryView":691 * 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":692 * * 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 == ((int)-1))) __PYX_ERR(3, 692, __pyx_L1_error) } __pyx_L6:; /* "View.MemoryView":679 * 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":694 * 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 == ((Py_ssize_t)-1))) __PYX_ERR(3, 694, __pyx_L1_error) __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); /* "View.MemoryView":695 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { /* "View.MemoryView":696 * 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_ERR(3, 696, __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__17); __Pyx_GIVEREF(__pyx_slice__17); PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__17); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(3, 696, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":695 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ } /* "View.MemoryView":698 * 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_ERR(3, 698, __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_ERR(3, 698, __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_ERR(3, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(3, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_11); __pyx_t_11 = 0; goto __pyx_L0; /* "View.MemoryView":666 * 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":700 * 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":701 * * 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":702 * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":703 * 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__18, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 703, __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_ERR(3, 703, __pyx_L1_error) /* "View.MemoryView":702 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ } } /* "View.MemoryView":700 * 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":710 * * @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":711 * @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":718 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< * * cdef _memoryviewslice memviewsliceobj */ (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); /* "View.MemoryView":722 * 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_ERR(3, 722, __pyx_L1_error) } } #endif /* "View.MemoryView":724 * 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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":725 * * 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_ERR(3, 725, __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":726 * 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); /* "View.MemoryView":724 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ goto __pyx_L3; } /* "View.MemoryView":728 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< * p_src = &src * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); /* "View.MemoryView":729 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< * * */ __pyx_v_p_src = (&__pyx_v_src); } __pyx_L3:; /* "View.MemoryView":735 * * * 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":736 * * 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":741 * * * 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":742 * * 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":746 * 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_ERR(3, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 746, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 746, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } else { if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(3, 746, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #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(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(3, 746, __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":747 * * 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":751 * 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_ERR(3, 751, __pyx_L1_error) /* "View.MemoryView":748 * 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 == ((int)-1))) __PYX_ERR(3, 748, __pyx_L1_error) /* "View.MemoryView":747 * * 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], */ goto __pyx_L6; } /* "View.MemoryView":754 * 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":755 * 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":756 * 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":757 * 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]) = -1L; /* "View.MemoryView":758 * 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); /* "View.MemoryView":754 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ goto __pyx_L6; } /* "View.MemoryView":760 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< * stop = index.stop or 0 * step = index.step or 0 */ /*else*/ { __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 760, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(3, 760, __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_ERR(3, 760, __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":761 * 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_ERR(3, 761, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(3, 761, __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_ERR(3, 761, __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":762 * 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_ERR(3, 762, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(3, 762, __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_ERR(3, 762, __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":764 * 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_ERR(3, 764, __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":765 * * 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_ERR(3, 765, __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":766 * 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_ERR(3, 766, __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":768 * 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 == ((int)-1))) __PYX_ERR(3, 768, __pyx_L1_error) /* "View.MemoryView":774 * 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":746 * 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":776 * 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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":777 * * 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":778 * 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_ERR(3, 778, __pyx_L1_error) } /* "View.MemoryView":779 * 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_ERR(3, 779, __pyx_L1_error) } /* "View.MemoryView":777 * * 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_ERR(3, 777, __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_ERR(3, 777, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":776 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ } /* "View.MemoryView":782 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ /*else*/ { __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":783 * 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_ERR(3, 782, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":782 * 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_ERR(3, 782, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":710 * * @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":807 * * @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":827 * 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":829 * 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":830 * * 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); /* "View.MemoryView":829 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ } /* "View.MemoryView":831 * 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":832 * 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, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(3, 832, __pyx_L1_error) /* "View.MemoryView":831 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ } /* "View.MemoryView":827 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ goto __pyx_L3; } /* "View.MemoryView":835 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< * * if have_step and step == 0: */ /*else*/ { __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":837 * 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":838 * * 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, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(3, 838, __pyx_L1_error) /* "View.MemoryView":837 * 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) * */ } /* "View.MemoryView":841 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { /* "View.MemoryView":842 * * 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":843 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< * if start < 0: * start = 0 */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":844 * 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":845 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< * elif start >= shape: * if negative_step: */ __pyx_v_start = 0; /* "View.MemoryView":844 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ } /* "View.MemoryView":842 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ goto __pyx_L12; } /* "View.MemoryView":846 * 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":847 * 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":848 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":847 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L14; } /* "View.MemoryView":850 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ /*else*/ { __pyx_v_start = __pyx_v_shape; } __pyx_L14:; /* "View.MemoryView":846 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ } __pyx_L12:; /* "View.MemoryView":841 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ goto __pyx_L11; } /* "View.MemoryView":852 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":853 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":852 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L15; } /* "View.MemoryView":855 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ /*else*/ { __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; /* "View.MemoryView":857 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { /* "View.MemoryView":858 * * 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":859 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< * if stop < 0: * stop = 0 */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); /* "View.MemoryView":860 * 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":861 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< * elif stop > shape: * stop = shape */ __pyx_v_stop = 0; /* "View.MemoryView":860 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ } /* "View.MemoryView":858 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ goto __pyx_L17; } /* "View.MemoryView":862 * 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":863 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_stop = __pyx_v_shape; /* "View.MemoryView":862 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ } __pyx_L17:; /* "View.MemoryView":857 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ goto __pyx_L16; } /* "View.MemoryView":865 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":866 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ __pyx_v_stop = -1L; /* "View.MemoryView":865 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ goto __pyx_L19; } /* "View.MemoryView":868 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ /*else*/ { __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; /* "View.MemoryView":870 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":871 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< * * */ __pyx_v_step = 1; /* "View.MemoryView":870 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ } /* "View.MemoryView":875 * * 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":877 * 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":878 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< * * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); /* "View.MemoryView":877 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ } /* "View.MemoryView":880 * 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":881 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< * * */ __pyx_v_new_shape = 0; /* "View.MemoryView":880 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ } /* "View.MemoryView":884 * * * 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":885 * * 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":886 * 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":889 * * * 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":890 * * 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)); /* "View.MemoryView":889 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ goto __pyx_L23; } /* "View.MemoryView":892 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< * * if suboffset >= 0: */ /*else*/ { __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":894 * 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":895 * * 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":896 * 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":897 * 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); /* "View.MemoryView":896 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ goto __pyx_L26; } /* "View.MemoryView":899 * dst.data = (<char **> dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< * "must be indexed and not sliced", dim) * else: */ /*else*/ { /* "View.MemoryView":900 * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< * else: * suboffset_dim[0] = new_ndim */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(3, 899, __pyx_L1_error) } __pyx_L26:; /* "View.MemoryView":895 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ goto __pyx_L25; } /* "View.MemoryView":902 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< * * return 0 */ /*else*/ { (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; } __pyx_L25:; /* "View.MemoryView":894 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ } /* "View.MemoryView":904 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":807 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":910 * * @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":912 * 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 = -1L; /* "View.MemoryView":913 * 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":916 * 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":917 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< * stride = itemsize * else: */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(3, 917, __pyx_L1_error) } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(3, 917, __pyx_L1_error) } __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); /* "View.MemoryView":918 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< * else: * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; /* "View.MemoryView":916 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ goto __pyx_L3; } /* "View.MemoryView":920 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< * stride = view.strides[dim] * if view.suboffsets != NULL: */ /*else*/ { __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); /* "View.MemoryView":921 * 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":922 * 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":923 * 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]); /* "View.MemoryView":922 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ } } __pyx_L3:; /* "View.MemoryView":925 * 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":926 * * 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":927 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":928 * 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_ERR(3, 928, __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_ERR(3, 928, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 928, __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_ERR(3, 928, __pyx_L1_error) /* "View.MemoryView":927 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":925 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ } /* "View.MemoryView":930 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":931 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 931, __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_ERR(3, 931, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 931, __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_ERR(3, 931, __pyx_L1_error) /* "View.MemoryView":930 * 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) * */ } /* "View.MemoryView":933 * 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":934 * * 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":935 * 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); /* "View.MemoryView":934 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ } /* "View.MemoryView":937 * resultp = (<char **> resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_resultp; goto __pyx_L0; /* "View.MemoryView":910 * * @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":943 * * @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; long __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":944 * @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":946 * 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":947 * * 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":951 * * 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); __pyx_t_4 = __pyx_t_3; for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":952 * 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":953 * 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_5 = (__pyx_v_strides[__pyx_v_j]); __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; /* "View.MemoryView":954 * 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_6 = (__pyx_v_shape[__pyx_v_j]); __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; /* "View.MemoryView":956 * 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_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); if (!__pyx_t_8) { } else { __pyx_t_7 = __pyx_t_8; goto __pyx_L6_bool_binop_done; } __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); __pyx_t_7 = __pyx_t_8; __pyx_L6_bool_binop_done:; if (__pyx_t_7) { /* "View.MemoryView":957 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(3, 957, __pyx_L1_error) /* "View.MemoryView":956 * 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") * */ } } /* "View.MemoryView":959 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< * * */ __pyx_r = 1; goto __pyx_L0; /* "View.MemoryView":943 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":976 * 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":977 * * 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":976 * 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":979 * __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":980 * * 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":981 * 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_ERR(3, 981, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":980 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ } /* "View.MemoryView":983 * 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): */ /*else*/ { __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_ERR(3, 983, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /* "View.MemoryView":979 * __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":985 * 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":986 * * 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":987 * 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 == ((int)0))) __PYX_ERR(3, 987, __pyx_L1_error) /* "View.MemoryView":986 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ goto __pyx_L3; } /* "View.MemoryView":989 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< * * @property */ /*else*/ { __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_ERR(3, 989, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; /* "View.MemoryView":985 * 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":992 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(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":993 * @property * def base(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":992 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_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("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(3, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { 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("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(3, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":999 * * @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":1007 * 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":1008 * * if <PyObject *> memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; /* "View.MemoryView":1007 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ } /* "View.MemoryView":1013 * * * 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_ERR(3, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1013, __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":1015 * 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":1016 * * 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":1018 * __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_ERR(3, 1018, __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":1019 * * 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":1021 * 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":1022 * * 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":1023 * 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":1024 * 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":1025 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: */ Py_INCREF(Py_None); /* "View.MemoryView":1027 * Py_INCREF(Py_None) * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< * result.flags = PyBUF_RECORDS * else: */ __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); if (__pyx_t_1) { /* "View.MemoryView":1028 * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< * else: * result.flags = PyBUF_RECORDS_RO */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; /* "View.MemoryView":1027 * Py_INCREF(Py_None) * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< * result.flags = PyBUF_RECORDS * else: */ goto __pyx_L4; } /* "View.MemoryView":1030 * result.flags = PyBUF_RECORDS * else: * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< * * result.view.shape = <Py_ssize_t *> result.from_slice.shape */ /*else*/ { __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; } __pyx_L4:; /* "View.MemoryView":1032 * result.flags = PyBUF_RECORDS_RO * * 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":1033 * * 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":1036 * * * 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":1037 * * 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":1038 * 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":1039 * 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":1040 * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ goto __pyx_L6_break; /* "View.MemoryView":1038 * 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_L6_break:; /* "View.MemoryView":1042 * 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":1043 * * 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_ERR(3, 1043, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":1044 * 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_ERR(3, 1044, __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_ERR(3, 1044, __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_ERR(3, 1044, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } /* "View.MemoryView":1046 * 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":1047 * * 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":1049 * 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":999 * * @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":1052 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice) except NULL: * 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":1055 * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1056 * 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_ERR(3, 1056, __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":1057 * 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; /* "View.MemoryView":1055 * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ } /* "View.MemoryView":1059 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); /* "View.MemoryView":1060 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_slice_copy') */ __pyx_r = __pyx_v_mslice; goto __pyx_L0; } /* "View.MemoryView":1052 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1063 * * @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; int __pyx_t_4; Py_ssize_t __pyx_t_5; __Pyx_RefNannySetupContext("slice_copy", 0); /* "View.MemoryView":1067 * 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":1068 * * 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":1069 * 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":1071 * 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":1072 * * 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":1074 * 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; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_dim = __pyx_t_4; /* "View.MemoryView":1075 * * 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":1076 * 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":1077 * 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_5 = (__pyx_v_suboffsets[__pyx_v_dim]); } else { __pyx_t_5 = -1L; } (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; } /* "View.MemoryView":1063 * * @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":1080 * * @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":1083 * "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":1084 * 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_ERR(3, 1084, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":1080 * * @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":1087 * * @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":1094 * 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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1095 * * 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":1096 * 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; /* "View.MemoryView":1094 * 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 */ goto __pyx_L3; } /* "View.MemoryView":1098 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< * to_dtype_func = NULL * */ /*else*/ { __pyx_v_to_object_func = NULL; /* "View.MemoryView":1099 * 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":1101 * 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":1103 * 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_ERR(3, 1101, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":1087 * * @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":1109 * * * 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":1110 * * 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":1111 * 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; /* "View.MemoryView":1110 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ } /* "View.MemoryView":1113 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ /*else*/ { __pyx_r = __pyx_v_arg; goto __pyx_L0; } /* "View.MemoryView":1109 * * * 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":1116 * * @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; int __pyx_t_4; /* "View.MemoryView":1121 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< * cdef Py_ssize_t f_stride = 0 * */ __pyx_v_c_stride = 0; /* "View.MemoryView":1122 * 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":1124 * 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":1125 * * 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":1126 * 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":1127 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * for i in range(ndim): */ goto __pyx_L4_break; /* "View.MemoryView":1125 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ } } __pyx_L4_break:; /* "View.MemoryView":1129 * break * * for i in range(ndim): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] */ __pyx_t_1 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_1; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1130 * * 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":1131 * 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":1132 * 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; /* "View.MemoryView":1130 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ } } __pyx_L7_break:; /* "View.MemoryView":1134 * 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":1135 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< * else: * return 'F' */ __pyx_r = 'C'; goto __pyx_L0; /* "View.MemoryView":1134 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ } /* "View.MemoryView":1137 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ /*else*/ { __pyx_r = 'F'; goto __pyx_L0; } /* "View.MemoryView":1116 * * @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":1140 * * @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; Py_ssize_t __pyx_t_6; /* "View.MemoryView":1147 * * 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":1148 * 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":1149 * 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":1150 * 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":1152 * 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":1153 * * 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":1154 * 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:; /* "View.MemoryView":1153 * * 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) */ if (__pyx_t_1) { /* "View.MemoryView":1155 * 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): */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); /* "View.MemoryView":1153 * * 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) */ goto __pyx_L4; } /* "View.MemoryView":1157 * 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 */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1158 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< * src_data += src_stride * dst_data += dst_stride */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); /* "View.MemoryView":1159 * 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":1160 * 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:; /* "View.MemoryView":1152 * 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): */ goto __pyx_L3; } /* "View.MemoryView":1162 * 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, */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1163 * 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":1167 * 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":1168 * 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":1140 * * @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":1170 * 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":1173 * __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":1170 * 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":1177 * * @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 Py_ssize_t shape, size = src.memview.view.itemsize */ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { Py_ssize_t __pyx_v_shape; Py_ssize_t __pyx_v_size; Py_ssize_t __pyx_r; Py_ssize_t __pyx_t_1; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; /* "View.MemoryView":1179 * 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 Py_ssize_t shape, size = src.memview.view.itemsize # <<<<<<<<<<<<<< * * for shape in src.shape[:ndim]: */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_size = __pyx_t_1; /* "View.MemoryView":1181 * cdef Py_ssize_t shape, size = src.memview.view.itemsize * * for shape in src.shape[:ndim]: # <<<<<<<<<<<<<< * size *= shape * */ __pyx_t_3 = (__pyx_v_src->shape + __pyx_v_ndim); for (__pyx_t_4 = __pyx_v_src->shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { __pyx_t_2 = __pyx_t_4; __pyx_v_shape = (__pyx_t_2[0]); /* "View.MemoryView":1182 * * for shape in src.shape[:ndim]: * size *= shape # <<<<<<<<<<<<<< * * return size */ __pyx_v_size = (__pyx_v_size * __pyx_v_shape); } /* "View.MemoryView":1184 * size *= shape * * return size # <<<<<<<<<<<<<< * * @cname('__pyx_fill_contig_strides_array') */ __pyx_r = __pyx_v_size; goto __pyx_L0; /* "View.MemoryView":1177 * * @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 Py_ssize_t shape, size = src.memview.view.itemsize */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1187 * * @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; int __pyx_t_4; /* "View.MemoryView":1196 * 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":1197 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< * strides[idx] = stride * stride *= shape[idx] */ __pyx_t_2 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_idx = __pyx_t_4; /* "View.MemoryView":1198 * if order == 'F': * for idx in range(ndim): * strides[idx] = stride # <<<<<<<<<<<<<< * stride *= shape[idx] * else: */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1199 * for idx in range(ndim): * strides[idx] = 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])); } /* "View.MemoryView":1196 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ goto __pyx_L3; } /* "View.MemoryView":1201 * stride *= shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * strides[idx] = stride * stride *= shape[idx] */ /*else*/ { for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; /* "View.MemoryView":1202 * else: * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride # <<<<<<<<<<<<<< * stride *= shape[idx] * */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1203 * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride * stride *= shape[idx] # <<<<<<<<<<<<<< * * return stride */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } } __pyx_L3:; /* "View.MemoryView":1205 * stride *= shape[idx] * * return stride # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_data_to_temp') */ __pyx_r = __pyx_v_stride; goto __pyx_L0; /* "View.MemoryView":1187 * * @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":1208 * * @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_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1219 * 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":1220 * * 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":1222 * 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":1223 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1224 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(3, 1224, __pyx_L1_error) /* "View.MemoryView":1223 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ } /* "View.MemoryView":1227 * * * tmpslice.data = <char *> result # <<<<<<<<<<<<<< * tmpslice.memview = src.memview * for i in range(ndim): */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); /* "View.MemoryView":1228 * * 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":1229 * 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; __pyx_t_5 = __pyx_t_3; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1230 * 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":1231 * 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]) = -1L; } /* "View.MemoryView":1233 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< * ndim, order) * */ (void)(__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":1237 * * * for i in range(ndim): # <<<<<<<<<<<<<< * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 */ __pyx_t_3 = __pyx_v_ndim; __pyx_t_5 = __pyx_t_3; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1238 * * 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":1239 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< * * if slice_is_contig(src[0], order, ndim): */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; /* "View.MemoryView":1238 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ } } /* "View.MemoryView":1241 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1242 * * if slice_is_contig(src[0], order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); /* "View.MemoryView":1241 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ goto __pyx_L9; } /* "View.MemoryView":1244 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< * * return result */ /*else*/ { copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); } __pyx_L9:; /* "View.MemoryView":1246 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":1208 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1251 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); /* "View.MemoryView":1254 * 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_ERR(3, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; /* "View.MemoryView":1253 * 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_ERR(3, 1253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 1253, __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_ERR(3, 1253, __pyx_L1_error) /* "View.MemoryView":1251 * * @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 __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1257 * * @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; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1258 * @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_ERR(3, 1258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 1258, __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_ERR(3, 1258, __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_UNPACK_METHODS && 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); } } __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 1258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __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_ERR(3, 1258, __pyx_L1_error) /* "View.MemoryView":1257 * * @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_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1261 * * @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; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1262 * @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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":1263 * 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_ERR(3, 1263, __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_UNPACK_METHODS && 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); } } __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1263, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __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_ERR(3, 1263, __pyx_L1_error) /* "View.MemoryView":1262 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ } /* "View.MemoryView":1265 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_contents') */ /*else*/ { __Pyx_Raise(__pyx_v_error, 0, 0, 0); __PYX_ERR(3, 1265, __pyx_L1_error) } /* "View.MemoryView":1261 * * @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_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1268 * * @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; int __pyx_t_6; void *__pyx_t_7; int __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1276 * 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":1277 * """ * 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":1279 * 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":1280 * 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":1281 * 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":1284 * 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":1285 * * 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); /* "View.MemoryView":1284 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ goto __pyx_L3; } /* "View.MemoryView":1286 * 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":1287 * 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); /* "View.MemoryView":1286 * 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_L3:; /* "View.MemoryView":1289 * 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":1291 * 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; __pyx_t_3 = __pyx_t_5; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1292 * * 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":1293 * 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":1294 * 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":1295 * 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; /* "View.MemoryView":1293 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ goto __pyx_L7; } /* "View.MemoryView":1297 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ /*else*/ { __pyx_t_6 = __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_6 == ((int)-1))) __PYX_ERR(3, 1297, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":1292 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ } /* "View.MemoryView":1299 * _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":1300 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(3, 1300, __pyx_L1_error) /* "View.MemoryView":1299 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ } } /* "View.MemoryView":1302 * _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":1304 * 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":1305 * * 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); /* "View.MemoryView":1304 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ } /* "View.MemoryView":1307 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(3, 1307, __pyx_L1_error) __pyx_v_tmpdata = __pyx_t_7; /* "View.MemoryView":1308 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< * * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; /* "View.MemoryView":1302 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(src, order, ndim): */ } /* "View.MemoryView":1310 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1313 * * * 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":1314 * * 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); /* "View.MemoryView":1313 * * * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): */ goto __pyx_L12; } /* "View.MemoryView":1315 * 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":1316 * 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); /* "View.MemoryView":1315 * 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_L12:; /* "View.MemoryView":1318 * 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":1320 * 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":1321 * * 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) */ (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); /* "View.MemoryView":1322 * 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":1323 * 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":1324 * 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; /* "View.MemoryView":1318 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ } /* "View.MemoryView":1310 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1326 * 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_8 = (__pyx_t_2 != 0); if (__pyx_t_8) { /* "View.MemoryView":1329 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(3, 1329, __pyx_L1_error) /* "View.MemoryView":1330 * * 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 == ((int)0))) __PYX_ERR(3, 1330, __pyx_L1_error) /* "View.MemoryView":1326 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1332 * 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":1333 * * 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":1334 * 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":1336 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1337 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_broadcast_leading') */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1268 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1340 * * @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; int __pyx_t_3; /* "View.MemoryView":1344 * 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":1346 * 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":1347 * * 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":1348 * 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":1349 * 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":1351 * 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; __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1352 * * 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":1353 * 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":1354 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1340 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ /* function exit code */ } /* "View.MemoryView":1362 * * @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":1366 * * * 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":1367 * * 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); /* "View.MemoryView":1366 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ } /* "View.MemoryView":1362 * * @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":1371 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); /* "View.MemoryView":1374 * 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":1371 * * @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 __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } /* "View.MemoryView":1377 * * @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; Py_ssize_t __pyx_t_3; int __pyx_t_4; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); /* "View.MemoryView":1381 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< * if ndim == 1: * if inc: */ __pyx_t_1 = (__pyx_v_shape[0]); __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1382 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_4) { /* "View.MemoryView":1383 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ __pyx_t_4 = (__pyx_v_inc != 0); if (__pyx_t_4) { /* "View.MemoryView":1384 * if ndim == 1: * if inc: * Py_INCREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * Py_DECREF((<PyObject **> data)[0]) */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); /* "View.MemoryView":1383 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ goto __pyx_L6; } /* "View.MemoryView":1386 * Py_INCREF((<PyObject **> data)[0]) * else: * Py_DECREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, */ /*else*/ { Py_DECREF((((PyObject **)__pyx_v_data)[0])); } __pyx_L6:; /* "View.MemoryView":1382 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ goto __pyx_L5; } /* "View.MemoryView":1388 * Py_DECREF((<PyObject **> data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * */ /*else*/ { /* "View.MemoryView":1389 * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, * ndim - 1, inc) # <<<<<<<<<<<<<< * * data += strides[0] */ __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":1391 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } /* "View.MemoryView":1377 * * @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":1397 * * @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":1400 * 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":1401 * 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":1403 * _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":1397 * * @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":1407 * * @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; Py_ssize_t __pyx_t_4; /* "View.MemoryView":1411 * 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":1412 * 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":1414 * 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":1415 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< * memcpy(data, item, itemsize) * data += stride */ __pyx_t_2 = __pyx_v_extent; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1416 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< * data += stride * else: */ (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); /* "View.MemoryView":1417 * 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); } /* "View.MemoryView":1414 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ goto __pyx_L3; } /* "View.MemoryView":1419 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) */ /*else*/ { __pyx_t_2 = __pyx_v_extent; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1420 * 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":1422 * _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":1407 * * @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 */ } /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v___pyx_type = 0; long __pyx_v___pyx_checksum; PyObject *__pyx_v___pyx_state = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,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); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(3, 1, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(3, 1, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(3, 1, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { 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); } __pyx_v___pyx_type = values[0]; __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(3, 1, __pyx_L3_error) __pyx_v___pyx_state = values[2]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(3, 1, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_v___pyx_PickleError = 0; PyObject *__pyx_v___pyx_result = 0; PyObject *__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_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); /* "(tree fragment)":4 * cdef object __pyx_PickleError * cdef object __pyx_result * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) */ __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); if (__pyx_t_1) { /* "(tree fragment)":5 * cdef object __pyx_result * if __pyx_checksum != 0xb068931: * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) */ __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_n_s_PickleError); __Pyx_GIVEREF(__pyx_n_s_PickleError); PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_2); __pyx_v___pyx_PickleError = __pyx_t_2; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":6 * if __pyx_checksum != 0xb068931: * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: */ __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_INCREF(__pyx_v___pyx_PickleError); __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(3, 6, __pyx_L1_error) /* "(tree fragment)":4 * cdef object __pyx_PickleError * cdef object __pyx_result * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) */ } /* "(tree fragment)":7 * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v___pyx_result = __pyx_t_3; __pyx_t_3 = 0; /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result */ __pyx_t_1 = (__pyx_v___pyx_state != Py_None); __pyx_t_6 = (__pyx_t_1 != 0); if (__pyx_t_6) { /* "(tree fragment)":9 * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) # <<<<<<<<<<<<<< * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): */ if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(3, 9, __pyx_L1_error) __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result */ } /* "(tree fragment)":10 * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result # <<<<<<<<<<<<<< * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v___pyx_result); __pyx_r = __pyx_v___pyx_result; goto __pyx_L0; /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_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.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v___pyx_PickleError); __Pyx_XDECREF(__pyx_v___pyx_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; Py_ssize_t __pyx_t_3; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); /* "(tree fragment)":12 * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): * __pyx_result.__dict__.update(__pyx_state[1]) */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(3, 12, __pyx_L1_error) } __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __Pyx_GOTREF(__pyx_v___pyx_result->name); __Pyx_DECREF(__pyx_v___pyx_result->name); __pyx_v___pyx_result->name = __pyx_t_1; __pyx_t_1 = 0; /* "(tree fragment)":13 * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< * __pyx_result.__dict__.update(__pyx_state[1]) */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(3, 13, __pyx_L1_error) } __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(3, 13, __pyx_L1_error) __pyx_t_4 = ((__pyx_t_3 > 1) != 0); if (__pyx_t_4) { } else { __pyx_t_2 = __pyx_t_4; goto __pyx_L4_bool_binop_done; } __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(3, 13, __pyx_L1_error) __pyx_t_5 = (__pyx_t_4 != 0); __pyx_t_2 = __pyx_t_5; __pyx_L4_bool_binop_done:; if (__pyx_t_2) { /* "(tree fragment)":14 * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< */ __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(3, 14, __pyx_L1_error) } __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); if (likely(__pyx_t_8)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_8); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_7, function); } } __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":13 * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< * __pyx_result.__dict__.update(__pyx_state[1]) */ } /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /* 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_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static struct __pyx_vtabstruct_array __pyx_vtable_array; 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->__pyx_vtab = __pyx_vtabptr_array; 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)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_array(PyObject *o) { struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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); __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); __pyx_array___dealloc__(o); __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); 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 = __Pyx_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 __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); } static PyMethodDef __pyx_methods_array[] = { {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_array[] = { {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_array = { __pyx_array___len__, /*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 = { __pyx_array___len__, /*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) "mds_cython.array", /*tp_name*/ sizeof(struct __pyx_array_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_array, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #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 CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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[] = { {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_MemviewEnum = { PyVarObject_HEAD_INIT(0, 0) "mds_cython.Enum", /*tp_name*/ sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_Enum, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #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)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_memoryview(PyObject *o) { struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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); __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); __pyx_memoryview___dealloc__(o); __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); 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_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(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}, {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_memoryview[] = { {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)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) "mds_cython.memoryview", /*tp_name*/ sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #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 CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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); __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); __pyx_memoryviewslice___dealloc__(o); __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); 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_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_memoryviewslice = { PyVarObject_HEAD_INIT(0, 0) "mds_cython._memoryviewslice", /*tp_name*/ sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static PyMethodDef __pyx_methods[] = { {"_dyevr", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10mds_cython_1_dyevr, METH_VARARGS|METH_KEYWORDS, 0}, {"cython_dsyevr_inplace", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10mds_cython_3cython_dsyevr_inplace, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10mds_cython_2cython_dsyevr_inplace}, {"cython_cmds_fortran_inplace", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10mds_cython_7cython_cmds_fortran_inplace, METH_VARARGS|METH_KEYWORDS, 0}, {"dist_matrix_subset", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10mds_cython_9dist_matrix_subset, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10mds_cython_8dist_matrix_subset}, {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec_mds_cython(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec_mds_cython}, {0, NULL} }; #endif static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "mds_cython", 0, /* m_doc */ #if CYTHON_PEP489_MULTI_PHASE_INIT 0, /* m_size */ #else -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif #ifndef CYTHON_SMALL_CODE #if defined(__clang__) #define CYTHON_SMALL_CODE #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define CYTHON_SMALL_CODE __attribute__((cold)) #else #define CYTHON_SMALL_CODE #endif #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_A, __pyx_k_A, sizeof(__pyx_k_A), 0, 0, 1, 1}, {&__pyx_n_s_ABS_TOL, __pyx_k_ABS_TOL, sizeof(__pyx_k_ABS_TOL), 0, 0, 1, 1}, {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 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_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 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_D, __pyx_k_D, sizeof(__pyx_k_D), 0, 0, 1, 1}, {&__pyx_n_s_D_reuse, __pyx_k_D_reuse, sizeof(__pyx_k_D_reuse), 0, 0, 1, 1}, {&__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_n_u_F, __pyx_k_F, sizeof(__pyx_k_F), 0, 1, 0, 1}, {&__pyx_n_s_FLOAT64, __pyx_k_FLOAT64, sizeof(__pyx_k_FLOAT64), 0, 0, 1, 1}, {&__pyx_n_s_IL, __pyx_k_IL, sizeof(__pyx_k_IL), 0, 0, 1, 1}, {&__pyx_n_s_ISUPPZ, __pyx_k_ISUPPZ, sizeof(__pyx_k_ISUPPZ), 0, 0, 1, 1}, {&__pyx_n_s_IU, __pyx_k_IU, sizeof(__pyx_k_IU), 0, 0, 1, 1}, {&__pyx_n_s_IWORK, __pyx_k_IWORK, sizeof(__pyx_k_IWORK), 0, 0, 1, 1}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 0, 0, 1, 0}, {&__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_M, __pyx_k_M, sizeof(__pyx_k_M), 0, 0, 1, 1}, {&__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_n_s_N, __pyx_k_N, sizeof(__pyx_k_N), 0, 0, 1, 1}, {&__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_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 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_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, {&__pyx_n_s_W, __pyx_k_W, sizeof(__pyx_k_W), 0, 0, 1, 1}, {&__pyx_n_s_WORK, __pyx_k_WORK, sizeof(__pyx_k_WORK), 0, 0, 1, 1}, {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, {&__pyx_n_s_Z, __pyx_k_Z, sizeof(__pyx_k_Z), 0, 0, 1, 1}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_asfortranarray, __pyx_k_asfortranarray, sizeof(__pyx_k_asfortranarray), 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_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, {&__pyx_n_s_cnt, __pyx_k_cnt, sizeof(__pyx_k_cnt), 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_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, {&__pyx_n_s_cython_cmds_parallel, __pyx_k_cython_cmds_parallel, sizeof(__pyx_k_cython_cmds_parallel), 0, 0, 1, 1}, {&__pyx_n_s_cython_dsyevr, __pyx_k_cython_dsyevr, sizeof(__pyx_k_cython_dsyevr), 0, 0, 1, 1}, {&__pyx_n_s_d, __pyx_k_d, sizeof(__pyx_k_d), 0, 0, 1, 1}, {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, {&__pyx_n_u_double, __pyx_k_double, sizeof(__pyx_k_double), 0, 1, 0, 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_el, __pyx_k_el, sizeof(__pyx_k_el), 0, 0, 1, 1}, {&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 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_flatten_list_of_lists, __pyx_k_flatten_list_of_lists, sizeof(__pyx_k_flatten_list_of_lists), 0, 0, 1, 1}, {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 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_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 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_ind, __pyx_k_ind, sizeof(__pyx_k_ind), 0, 0, 1, 1}, {&__pyx_n_s_ind_len, __pyx_k_ind_len, sizeof(__pyx_k_ind_len), 0, 0, 1, 1}, {&__pyx_n_s_ind_vec, __pyx_k_ind_vec, sizeof(__pyx_k_ind_vec), 0, 0, 1, 1}, {&__pyx_n_s_int32, __pyx_k_int32, sizeof(__pyx_k_int32), 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_len, __pyx_k_len, sizeof(__pyx_k_len), 0, 0, 1, 1}, {&__pyx_n_s_local_n, __pyx_k_local_n, sizeof(__pyx_k_local_n), 0, 0, 1, 1}, {&__pyx_n_s_lst, __pyx_k_lst, sizeof(__pyx_k_lst), 0, 0, 1, 1}, {&__pyx_n_s_lst_of_lsts, __pyx_k_lst_of_lsts, sizeof(__pyx_k_lst_of_lsts), 0, 0, 1, 1}, {&__pyx_n_s_m, __pyx_k_m, sizeof(__pyx_k_m), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_map, __pyx_k_map, sizeof(__pyx_k_map), 0, 0, 1, 1}, {&__pyx_n_s_max_n, __pyx_k_max_n, sizeof(__pyx_k_max_n), 0, 0, 1, 1}, {&__pyx_n_s_mds_cython, __pyx_k_mds_cython, sizeof(__pyx_k_mds_cython), 0, 0, 1, 1}, {&__pyx_kp_s_mds_cython_pyx, __pyx_k_mds_cython_pyx, sizeof(__pyx_k_mds_cython_pyx), 0, 0, 1, 0}, {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, {&__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_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_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, {&__pyx_n_s_ni, __pyx_k_ni, sizeof(__pyx_k_ni), 0, 0, 1, 1}, {&__pyx_n_s_nj, __pyx_k_nj, sizeof(__pyx_k_nj), 0, 0, 1, 1}, {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, {&__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_kp_u_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 1, 0, 0}, {&__pyx_kp_u_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 1, 0, 0}, {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, {&__pyx_n_s_offset, __pyx_k_offset, sizeof(__pyx_k_offset), 0, 0, 1, 1}, {&__pyx_n_s_order, __pyx_k_order, sizeof(__pyx_k_order), 0, 0, 1, 1}, {&__pyx_n_s_output, __pyx_k_output, sizeof(__pyx_k_output), 0, 0, 1, 1}, {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, {&__pyx_n_s_pdist, __pyx_k_pdist, sizeof(__pyx_k_pdist), 0, 0, 1, 1}, {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 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_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 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_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, {&__pyx_n_s_scipy_spatial_distance, __pyx_k_scipy_spatial_distance, sizeof(__pyx_k_scipy_spatial_distance), 0, 0, 1, 1}, {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, {&__pyx_n_s_squareform, __pyx_k_squareform, sizeof(__pyx_k_squareform), 0, 0, 1, 1}, {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, {&__pyx_n_s_starts, __pyx_k_starts, sizeof(__pyx_k_starts), 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_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, {&__pyx_n_s_sum, __pyx_k_sum, sizeof(__pyx_k_sum), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_tolerance, __pyx_k_tolerance, sizeof(__pyx_k_tolerance), 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_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, {&__pyx_n_s_values, __pyx_k_values, sizeof(__pyx_k_values), 0, 0, 1, 1}, {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 113, __pyx_L1_error) __pyx_builtin_sum = __Pyx_GetBuiltinName(__pyx_n_s_sum); if (!__pyx_builtin_sum) __PYX_ERR(0, 251, __pyx_L1_error) __pyx_builtin_map = __Pyx_GetBuiltinName(__pyx_n_s_map); if (!__pyx_builtin_map) __PYX_ERR(0, 251, __pyx_L1_error) __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 255, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 109, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(2, 947, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(3, 133, __pyx_L1_error) __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(3, 2, __pyx_L1_error) __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(3, 404, __pyx_L1_error) __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(3, 613, __pyx_L1_error) __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(3, 832, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":947 * __pyx_import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple_)) __PYX_ERR(2, 947, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "../../opt/miniconda3/envs/tallem/lib/python3.9/site-packages/numpy/__init__.pxd":953 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(2, 953, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "View.MemoryView":133 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(3, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "View.MemoryView":136 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(3, 136, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "View.MemoryView":148 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(3, 148, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "View.MemoryView":176 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(3, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "View.MemoryView":192 * 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__7 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(3, 192, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(3, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(3, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "View.MemoryView":418 * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< * * have_slices, index = _unellipsify(index, self.view.ndim) */ __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(3, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); /* "View.MemoryView":495 * 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__11 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(3, 495, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); /* "View.MemoryView":520 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< * * if flags & PyBUF_ND: */ __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(3, 520, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__12); __Pyx_GIVEREF(__pyx_tuple__12); /* "View.MemoryView":570 * 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__13 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(3, 570, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); /* "View.MemoryView":577 * def suboffsets(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__14 = PyTuple_New(1); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(3, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__14); __Pyx_INCREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); PyTuple_SET_ITEM(__pyx_tuple__14, 0, __pyx_int_neg_1); __Pyx_GIVEREF(__pyx_tuple__14); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(3, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(3, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); /* "View.MemoryView":682 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_slice__17 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__17)) __PYX_ERR(3, 682, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__17); __Pyx_GIVEREF(__pyx_slice__17); /* "View.MemoryView":703 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(3, 703, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__18); __Pyx_GIVEREF(__pyx_tuple__18); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(3, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__19); __Pyx_GIVEREF(__pyx_tuple__19); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(3, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__20); __Pyx_GIVEREF(__pyx_tuple__20); /* "mds_cython.pyx":67 * # return((W[:m], Z)) * * def cython_dsyevr(x, IL, IU, tolerance): # <<<<<<<<<<<<<< * ''' * Computes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'x' */ __pyx_tuple__21 = PyTuple_Pack(11, __pyx_n_s_x, __pyx_n_s_IL, __pyx_n_s_IU, __pyx_n_s_tolerance, __pyx_n_s_n, __pyx_n_s_m, __pyx_n_s_W, __pyx_n_s_ISUPPZ, __pyx_n_s_Z, __pyx_n_s_WORK, __pyx_n_s_IWORK); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__21); __Pyx_GIVEREF(__pyx_tuple__21); __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(4, 0, 11, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__21, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_mds_cython_pyx, __pyx_n_s_cython_dsyevr, 67, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) __PYX_ERR(0, 67, __pyx_L1_error) /* "mds_cython.pyx":230 * @cython.boundscheck(False) * @cython.wraparound(False) * def cython_cmds_parallel(const double[::1, :] X, const int d, const int[:] ind_vec, const int[:] ind_len, const int max_n, double[::1, :] output): # <<<<<<<<<<<<<< * ''' * X := (d,n) matrix [columns-oriented (Fortran-style)] of points */ __pyx_tuple__23 = PyTuple_Pack(13, __pyx_n_s_X, __pyx_n_s_d, __pyx_n_s_ind_vec, __pyx_n_s_ind_len, __pyx_n_s_max_n, __pyx_n_s_output, __pyx_n_s_N, __pyx_n_s_D_reuse, __pyx_n_s_i, __pyx_n_s_ni, __pyx_n_s_nj, __pyx_n_s_local_n, __pyx_n_s_M); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(0, 230, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__23); __Pyx_GIVEREF(__pyx_tuple__23); __pyx_codeobj__24 = (PyObject*)__Pyx_PyCode_New(6, 0, 13, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__23, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_mds_cython_pyx, __pyx_n_s_cython_cmds_parallel, 230, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__24)) __PYX_ERR(0, 230, __pyx_L1_error) /* "mds_cython.pyx":250 * * import numpy as np * def flatten_list_of_lists(lst_of_lsts): # <<<<<<<<<<<<<< * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel */ __pyx_tuple__25 = PyTuple_Pack(8, __pyx_n_s_lst_of_lsts, __pyx_n_s_N, __pyx_n_s_starts, __pyx_n_s_values, __pyx_n_s_cnt, __pyx_n_s_i, __pyx_n_s_lst, __pyx_n_s_el); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(0, 250, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__25); __Pyx_GIVEREF(__pyx_tuple__25); __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(1, 0, 8, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__25, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_mds_cython_pyx, __pyx_n_s_flatten_list_of_lists, 250, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) __PYX_ERR(0, 250, __pyx_L1_error) /* "View.MemoryView":286 * 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_ERR(3, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__27); __Pyx_GIVEREF(__pyx_tuple__27); /* "View.MemoryView":287 * * 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_ERR(3, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__28); __Pyx_GIVEREF(__pyx_tuple__28); /* "View.MemoryView":288 * 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_ERR(3, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__29); __Pyx_GIVEREF(__pyx_tuple__29); /* "View.MemoryView":291 * * * 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_ERR(3, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__30); __Pyx_GIVEREF(__pyx_tuple__30); /* "View.MemoryView":292 * * 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_ERR(3, 292, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__31); __Pyx_GIVEREF(__pyx_tuple__31); /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ __pyx_tuple__32 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__32)) __PYX_ERR(3, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__32); __Pyx_GIVEREF(__pyx_tuple__32); __pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) __PYX_ERR(3, 1, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { /* InitThreads.init */ #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_float_1eneg_8 = PyFloat_FromDouble(1e-8); if (unlikely(!__pyx_float_1eneg_8)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_10 = PyInt_FromLong(10); if (unlikely(!__pyx_int_10)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_26 = PyInt_FromLong(26); if (unlikely(!__pyx_int_26)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ static int __Pyx_modinit_global_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); /*--- 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); __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); /*--- Variable export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); /*--- Function export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_type_init_code(void) { __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); /*--- Type init code ---*/ __pyx_vtabptr_array = &__pyx_vtable_array; __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(3, 105, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_array.tp_print = 0; #endif if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(3, 105, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(3, 105, __pyx_L1_error) __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(3, 279, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_MemviewEnum.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(3, 279, __pyx_L1_error) __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_ERR(3, 330, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_memoryview.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(3, 330, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(3, 330, __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_ERR(3, 965, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_memoryviewslice.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(3, 965, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(3, 965, __pyx_L1_error) __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_type_import_code(void) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(4, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(4, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("array"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 58, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_5array_array = __Pyx_ImportType(__pyx_t_1, "array", "array", sizeof(arrayobject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_5array_array) __PYX_ERR(1, 58, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 200, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5numpy_dtype = __Pyx_ImportType(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(2, 200, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(2, 223, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(2, 227, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(2, 239, __pyx_L1_error) __pyx_ptype_5numpy_generic = __Pyx_ImportType(__pyx_t_1, "numpy", "generic", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_generic) __PYX_ERR(2, 771, __pyx_L1_error) __pyx_ptype_5numpy_number = __Pyx_ImportType(__pyx_t_1, "numpy", "number", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_number) __PYX_ERR(2, 773, __pyx_L1_error) __pyx_ptype_5numpy_integer = __Pyx_ImportType(__pyx_t_1, "numpy", "integer", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_integer) __PYX_ERR(2, 775, __pyx_L1_error) __pyx_ptype_5numpy_signedinteger = __Pyx_ImportType(__pyx_t_1, "numpy", "signedinteger", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_signedinteger) __PYX_ERR(2, 777, __pyx_L1_error) __pyx_ptype_5numpy_unsignedinteger = __Pyx_ImportType(__pyx_t_1, "numpy", "unsignedinteger", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_unsignedinteger) __PYX_ERR(2, 779, __pyx_L1_error) __pyx_ptype_5numpy_inexact = __Pyx_ImportType(__pyx_t_1, "numpy", "inexact", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_inexact) __PYX_ERR(2, 781, __pyx_L1_error) __pyx_ptype_5numpy_floating = __Pyx_ImportType(__pyx_t_1, "numpy", "floating", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_floating) __PYX_ERR(2, 783, __pyx_L1_error) __pyx_ptype_5numpy_complexfloating = __Pyx_ImportType(__pyx_t_1, "numpy", "complexfloating", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_complexfloating) __PYX_ERR(2, 785, __pyx_L1_error) __pyx_ptype_5numpy_flexible = __Pyx_ImportType(__pyx_t_1, "numpy", "flexible", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_flexible) __PYX_ERR(2, 787, __pyx_L1_error) __pyx_ptype_5numpy_character = __Pyx_ImportType(__pyx_t_1, "numpy", "character", sizeof(PyObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_character) __PYX_ERR(2, 789, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(2, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_variable_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); /*--- Variable import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_import_code(void) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); /*--- Function import code ---*/ __pyx_t_1 = PyImport_ImportModule("scipy.linalg.cython_lapack"); if (!__pyx_t_1) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (__Pyx_ImportFunction(__pyx_t_1, "dsyevr", (void (**)(void))&__pyx_f_5scipy_6linalg_13cython_lapack_dsyevr, "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_RefNannyFinishContext(); return -1; } #ifndef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #elif PY_MAJOR_VERSION < 3 #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" void #else #define __Pyx_PyMODINIT_FUNC void #endif #else #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * #else #define __Pyx_PyMODINIT_FUNC PyObject * #endif #endif #if PY_MAJOR_VERSION < 3 __Pyx_PyMODINIT_FUNC initmds_cython(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC initmds_cython(void) #else __Pyx_PyMODINIT_FUNC PyInit_mds_cython(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC PyInit_mds_cython(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { #if PY_VERSION_HEX >= 0x030700A1 static PY_INT64_T main_interpreter_id = -1; PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); if (main_interpreter_id == -1) { main_interpreter_id = current_id; return (unlikely(current_id == -1)) ? -1 : 0; } else if (unlikely(main_interpreter_id != current_id)) #else static PyInterpreterState *main_interpreter = NULL; PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; if (!main_interpreter) { main_interpreter = current_interpreter; } else if (unlikely(main_interpreter != current_interpreter)) #endif { PyErr_SetString( PyExc_ImportError, "Interpreter change detected - this module can only be loaded into one interpreter per process."); return -1; } return 0; } static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { if (allow_none || value != Py_None) { result = PyDict_SetItemString(moddict, to_name, value); } Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; if (__Pyx_check_single_interpreter()) return NULL; if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static CYTHON_SMALL_CODE int __pyx_pymod_exec_mds_cython(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; static PyThread_type_lock __pyx_t_3[8]; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m) { if (__pyx_m == __pyx_pyinit_module) return 0; PyErr_SetString(PyExc_RuntimeError, "Module 'mds_cython' has already been imported. Re-initialisation is not supported."); return -1; } #elif PY_MAJOR_VERSION >= 3 if (__pyx_m) return __Pyx_NewRef(__pyx_m); #endif #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("__Pyx_PyMODINIT_FUNC PyInit_mds_cython(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pxy_PyFrame_Initialize_Offsets __Pxy_PyFrame_Initialize_Offsets(); #endif __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS PyEval_InitThreads(); #endif /*--- Module creation code ---*/ #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_m = __pyx_pyinit_module; Py_INCREF(__pyx_m); #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("mds_cython", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) #endif __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_b); __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_cython_runtime); if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __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_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_mds_cython) { if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "mds_cython")) { if (unlikely(PyDict_SetItemString(modules, "mds_cython", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(); (void)__Pyx_modinit_variable_export_code(); (void)__Pyx_modinit_function_export_code(); if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) (void)__Pyx_modinit_variable_import_code(); if (unlikely(__Pyx_modinit_function_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "mds_cython.pyx":5 * # distutils: extra_link_args=-fopenmp * import cython * import numpy as np # <<<<<<<<<<<<<< * * from cython cimport view */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":17 * from libc.math cimport sqrt * * from scipy.spatial.distance import squareform, pdist # for validation # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_n_s_squareform); __Pyx_GIVEREF(__pyx_n_s_squareform); PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_squareform); __Pyx_INCREF(__pyx_n_s_pdist); __Pyx_GIVEREF(__pyx_n_s_pdist); PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_pdist); __pyx_t_2 = __Pyx_Import(__pyx_n_s_scipy_spatial_distance, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_squareform); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_squareform, __pyx_t_1) < 0) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_pdist); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_pdist, __pyx_t_1) < 0) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "mds_cython.pyx":67 * # return((W[:m], Z)) * * def cython_dsyevr(x, IL, IU, tolerance): # <<<<<<<<<<<<<< * ''' * Computes all eigenvalues/vectors in range 1 <= IL <= IU <= N of an (N x N) real symmetric matrix 'x' */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_10mds_cython_5cython_dsyevr, NULL, __pyx_n_s_mds_cython); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_cython_dsyevr, __pyx_t_2) < 0) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "mds_cython.pyx":127 * * * FLOAT64 = np.float64 # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_float64); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 127, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_FLOAT64, __pyx_t_1) < 0) __PYX_ERR(0, 127, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":230 * @cython.boundscheck(False) * @cython.wraparound(False) * def cython_cmds_parallel(const double[::1, :] X, const int d, const int[:] ind_vec, const int[:] ind_len, const int max_n, double[::1, :] output): # <<<<<<<<<<<<<< * ''' * X := (d,n) matrix [columns-oriented (Fortran-style)] of points */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_10mds_cython_11cython_cmds_parallel, NULL, __pyx_n_s_mds_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 230, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_cython_cmds_parallel, __pyx_t_1) < 0) __PYX_ERR(0, 230, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":249 * * * import numpy as np # <<<<<<<<<<<<<< * def flatten_list_of_lists(lst_of_lsts): * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 249, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":250 * * import numpy as np * def flatten_list_of_lists(lst_of_lsts): # <<<<<<<<<<<<<< * N = sum(map(len, lst_of_lsts)) # number of elements in the flattened array * starts = np.empty(len(lst_of_lsts)+1, dtype=np.int32) # needs place for one sentinel */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_10mds_cython_13flatten_list_of_lists, NULL, __pyx_n_s_mds_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 250, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_flatten_list_of_lists, __pyx_t_1) < 0) __PYX_ERR(0, 250, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mds_cython.pyx":1 * # distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION # <<<<<<<<<<<<<< * # distutils: extra_compile_args=-fopenmp * # distutils: extra_link_args=-fopenmp */ __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":209 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * def __dealloc__(array self): */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 209, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(3, 209, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_array_type); /* "View.MemoryView":286 * 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_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(generic); __Pyx_DECREF_SET(generic, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":287 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(strided); __Pyx_DECREF_SET(strided, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":288 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect); __Pyx_DECREF_SET(indirect, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":291 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(contiguous); __Pyx_DECREF_SET(contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":292 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 292, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect_contiguous); __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":316 * * DEF THREAD_LOCKS_PREALLOCATED = 8 * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ * PyThread_allocate_lock(), */ __pyx_memoryview_thread_locks_used = 0; /* "View.MemoryView":317 * DEF THREAD_LOCKS_PREALLOCATED = 8 * cdef int __pyx_memoryview_thread_locks_used = 0 * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< * PyThread_allocate_lock(), * PyThread_allocate_lock(), */ __pyx_t_3[0] = PyThread_allocate_lock(); __pyx_t_3[1] = PyThread_allocate_lock(); __pyx_t_3[2] = PyThread_allocate_lock(); __pyx_t_3[3] = PyThread_allocate_lock(); __pyx_t_3[4] = PyThread_allocate_lock(); __pyx_t_3[5] = PyThread_allocate_lock(); __pyx_t_3[6] = PyThread_allocate_lock(); __pyx_t_3[7] = PyThread_allocate_lock(); memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_3, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); /* "View.MemoryView":549 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 549, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(3, 549, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryview_type); /* "View.MemoryView":995 * return self.from_object * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 995, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(3, 995, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryviewslice_type); /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(3, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init mds_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init mds_cython"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #elif PY_MAJOR_VERSION >= 3 return __pyx_m; #else return; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule(modname); if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* PyObjectGetAttrStr */ #if CYTHON_USE_TYPE_SLOTS 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); } #endif /* GetBuiltinName */ 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; } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; 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); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* WriteUnraisableException */ static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback, CYTHON_UNUSED int nogil) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_PyThreadState_declare #ifdef WITH_THREAD PyGILState_STATE state; if (nogil) state = PyGILState_Ensure(); #ifdef _MSC_VER else state = (PyGILState_STATE)-1; #endif #endif __Pyx_PyThreadState_assign __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); } #ifdef WITH_THREAD if (nogil) PyGILState_Release(state); #endif } /* RaiseArgTupleInvalid */ 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); } /* RaiseDoubleKeywords */ 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 } /* ParseKeywords */ 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_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 (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(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 (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(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; } /* None */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } /* MemviewSliceInit */ 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 (unlikely(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; } #ifndef Py_NO_RETURN #define Py_NO_RETURN #endif static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { va_list vargs; char msg[200]; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, fmt); #else va_start(vargs); #endif vsnprintf(msg, 200, fmt, vargs); va_end(vargs); Py_FatalError(msg); } 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 (unlikely(!memview || (PyObject *) memview == Py_None)) return; if (unlikely(__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 (unlikely(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 (unlikely(!memview || (PyObject *) memview == Py_None)) { memslice->memview = NULL; return; } if (unlikely(__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 (unlikely(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; } } /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { (void)inplace; (void)zerodivision_check; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a + b); if (likely((x^a) >= 0 || (x^b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_add(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } } x = a + b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla + llb; return PyLong_FromLongLong(llx); #endif } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("add", return NULL) result = ((double)a) + (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } #endif /* py_abs */ #if CYTHON_USE_PYLONG_INTERNALS static PyObject *__Pyx_PyLong_AbsNeg(PyObject *n) { if (likely(Py_SIZE(n) == -1)) { return PyLong_FromLong(((PyLongObject*)n)->ob_digit[0]); } #if CYTHON_COMPILING_IN_CPYTHON { PyObject *copy = _PyLong_Copy((PyLongObject*)n); if (likely(copy)) { __Pyx_SET_SIZE(copy, -Py_SIZE(copy)); } return copy; } #else return PyNumber_Negative(n); #endif } #endif /* PyDictVersioning */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { PyObject *dict = Py_TYPE(obj)->tp_dict; return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; } static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { PyObject **dictptr = NULL; Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; if (offset) { #if CYTHON_COMPILING_IN_CPYTHON dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); #else dictptr = _PyObject_GetDictPtr(obj); #endif } return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; } static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { PyObject *dict = Py_TYPE(obj)->tp_dict; if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) return 0; return obj_dict_version == __Pyx_get_object_dict_version(obj); } #endif /* GetModuleGlobalName */ #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } else if (unlikely(PyErr_Occurred())) { return NULL; } #else result = PyDict_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } #endif #else result = PyObject_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); } /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif #endif /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); int flags = PyCFunction_GET_FLAGS(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = Py_TYPE(func)->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 /* GetItemInt */ static 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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, wrapped_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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, wrapped_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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(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(__Pyx_is_valid_index(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)) return NULL; PyErr_Clear(); } } 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)); } /* PyObjectCallMethO */ #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 /* PyObjectCallNoArg */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, NULL, 0); } #endif #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) #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 /* PyObjectCallOneArg */ #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) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif if (likely(PyCFunction_Check(func))) { if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (__Pyx_PyFastCFunction_Check(func)) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* PyObjectCall2Args */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { PyObject *args, *result = NULL; #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyFunction_FastCall(function, args, 2); } #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyCFunction_FastCall(function, args, 2); } #endif args = PyTuple_New(2); if (unlikely(!args)) goto done; Py_INCREF(arg1); PyTuple_SET_ITEM(args, 0, arg1); Py_INCREF(arg2); PyTuple_SET_ITEM(args, 1, arg2); Py_INCREF(function); result = __Pyx_PyObject_Call(function, args, NULL); Py_DECREF(args); Py_DECREF(function); done: return result; } /* SliceObject */ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { #if CYTHON_USE_TYPE_SLOTS PyMappingMethods* mp; #if PY_MAJOR_VERSION < 3 PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; if (likely(ms && ms->sq_slice)) { if (!has_cstart) { if (_py_start && (*_py_start != Py_None)) { cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; } else cstart = 0; } if (!has_cstop) { if (_py_stop && (*_py_stop != Py_None)) { cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; } else cstop = PY_SSIZE_T_MAX; } if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { Py_ssize_t l = ms->sq_length(obj); if (likely(l >= 0)) { if (cstop < 0) { cstop += l; if (cstop < 0) cstop = 0; } if (cstart < 0) { cstart += l; if (cstart < 0) cstart = 0; } } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) goto bad; PyErr_Clear(); } } return ms->sq_slice(obj, cstart, cstop); } #endif mp = Py_TYPE(obj)->tp_as_mapping; if (likely(mp && mp->mp_subscript)) #endif { PyObject* result; PyObject *py_slice, *py_start, *py_stop; if (_py_slice) { py_slice = *_py_slice; } else { PyObject* owned_start = NULL; PyObject* owned_stop = NULL; if (_py_start) { py_start = *_py_start; } else { if (has_cstart) { owned_start = py_start = PyInt_FromSsize_t(cstart); if (unlikely(!py_start)) goto bad; } else py_start = Py_None; } if (_py_stop) { py_stop = *_py_stop; } else { if (has_cstop) { owned_stop = py_stop = PyInt_FromSsize_t(cstop); if (unlikely(!py_stop)) { Py_XDECREF(owned_start); goto bad; } } else py_stop = Py_None; } py_slice = PySlice_New(py_start, py_stop, Py_None); Py_XDECREF(owned_start); Py_XDECREF(owned_stop); if (unlikely(!py_slice)) goto bad; } #if CYTHON_USE_TYPE_SLOTS result = mp->mp_subscript(obj, py_slice); #else result = PyObject_GetItem(obj, py_slice); #endif if (!_py_slice) { Py_DECREF(py_slice); } return result; } PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); bad: return NULL; } /* SetItemInt */ static 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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); if ((!boundscheck) || likely(__Pyx_is_valid_index(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)) return -1; PyErr_Clear(); } } 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); } /* GetTopmostException */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) { _PyErr_StackItem *exc_info = tstate->exc_info; while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && exc_info->previous_item != NULL) { exc_info = exc_info->previous_item; } return exc_info; } #endif /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); *type = exc_info->exc_type; *value = exc_info->exc_value; *tb = exc_info->exc_traceback; #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; #endif Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = type; exc_info->exc_value = value; exc_info->exc_traceback = tb; #else 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; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1; } return 0; } static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; if (unlikely(PyTuple_Check(err))) return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; 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_FAST_THREAD_STATE 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_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = local_type; exc_info->exc_value = local_value; exc_info->exc_traceback = local_tb; } #else 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; #endif 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; } /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare 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_PyThreadState_assign __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) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } 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 (cause) { 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 = __Pyx_PyThreadState_Current; 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 /* ArgTypeTest */ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } else if (exact) { #if PY_MAJOR_VERSION == 2 if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(__Pyx_TypeCheck(obj, type))) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } /* BytesEquals */ 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; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t hash1, hash2; hash1 = ((PyBytesObject*)s1)->ob_shash; hash2 = ((PyBytesObject*)s2)->ob_shash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { return (equals == Py_NE); } #endif 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 } /* UnicodeEquals */ 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; } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; #if CYTHON_PEP393_ENABLED hash1 = ((PyASCIIObject*)s1)->hash; hash2 = ((PyASCIIObject*)s2)->hash; #else hash1 = ((PyUnicodeObject*)s1)->hash; hash2 = ((PyUnicodeObject*)s2)->hash; #endif if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { goto return_ne; } } #endif 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_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif 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 } /* None */ 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; } /* GetAttr */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_USE_TYPE_SLOTS #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); } /* ObjectGetItem */ #if CYTHON_USE_TYPE_SLOTS static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { PyObject *runerr; Py_ssize_t key_value; PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; if (unlikely(!(m && m->sq_item))) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); return NULL; } key_value = __Pyx_PyIndex_AsSsize_t(index); if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); } if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { PyErr_Clear(); PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); } return NULL; } static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; if (likely(m && m->mp_subscript)) { return m->mp_subscript(obj, key); } return __Pyx_PyObject_GetIndex(obj, key); } #endif /* decode_c_string */ 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))) { size_t slen = strlen(cstring); if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { PyErr_SetString(PyExc_OverflowError, "c-string too long to convert to Python"); return NULL; } length = (Py_ssize_t) slen; if (start < 0) { start += length; if (start < 0) start = 0; } if (stop < 0) stop += length; } if (unlikely(stop <= start)) return __Pyx_NewRef(__pyx_empty_unicode); length = stop - start; cstring += start; if (decode_func) { return decode_func(cstring, length, errors); } else { return PyUnicode_Decode(cstring, length, encoding, errors); } } /* GetAttr3 */ static PyObject *__Pyx_GetAttr3Default(PyObject *d) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) return NULL; __Pyx_PyErr_Clear(); Py_INCREF(d); return d; } static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { PyObject *r = __Pyx_GetAttr(o, n); return (likely(r)) ? r : __Pyx_GetAttr3Default(d); } /* RaiseTooManyValuesToUnpack */ 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); } /* RaiseNeedMoreValuesToUnpack */ 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"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(__Pyx_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* SwapException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = *type; exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else 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; #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #endif /* Import */ 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_MAJOR_VERSION < 3 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 ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_MAJOR_VERSION < 3 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_MAJOR_VERSION < 3 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } #if PY_MAJOR_VERSION == 2 static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { PyObject *exception, *value, *tb; int res; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&exception, &value, &tb); res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } if (!res) { res = PyObject_IsSubclass(err, exc_type2); if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } } __Pyx_ErrRestore(exception, value, tb); return res; } #else static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; if (!res) { res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } return res; } #endif static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; assert(PyExceptionClass_Check(exc_type)); n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { PyObject *t = PyTuple_GET_ITEM(tuple, i); #if PY_MAJOR_VERSION < 3 if (likely(exc_type == t)) return 1; #endif if (likely(PyExceptionClass_Check(t))) { if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1; } else { } } return 0; } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { if (likely(err == exc_type)) return 1; if (likely(PyExceptionClass_Check(err))) { if (likely(PyExceptionClass_Check(exc_type))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); } else if (likely(PyTuple_Check(exc_type))) { return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type); } else { } } return PyErr_GivenExceptionMatches(err, exc_type); } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { assert(PyExceptionClass_Check(exc_type1)); assert(PyExceptionClass_Check(exc_type2)); if (likely(err == exc_type1 || err == exc_type2)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); } return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); } #endif /* None */ 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; } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* HasAttr */ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { PyObject *r; if (unlikely(!__Pyx_PyBaseString_Check(n))) { PyErr_SetString(PyExc_TypeError, "hasattr(): attribute name must be string"); return -1; } r = __Pyx_GetAttr(o, n); if (unlikely(!r)) { PyErr_Clear(); return 0; } else { Py_DECREF(r); return 1; } } /* PyObject_GenericGetAttrNoDict */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, attr_name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(attr_name)); #endif return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { PyObject *descr; PyTypeObject *tp = Py_TYPE(obj); if (unlikely(!PyString_Check(attr_name))) { return PyObject_GenericGetAttr(obj, attr_name); } assert(!tp->tp_dictoffset); descr = _PyType_Lookup(tp, attr_name); if (unlikely(!descr)) { return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); } Py_INCREF(descr); #if PY_MAJOR_VERSION < 3 if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) #endif { descrgetfunc f = Py_TYPE(descr)->tp_descr_get; if (unlikely(f)) { PyObject *res = f(descr, obj, (PyObject *)tp); Py_DECREF(descr); return res; } } return descr; } #endif /* PyObject_GenericGetAttr */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { return PyObject_GenericGetAttr(obj, attr_name); } return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); } #endif /* SetVTable */ 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; } /* PyObjectGetAttrStrNoError */ static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) __Pyx_PyErr_Clear(); } static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { PyObject *result; #if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); } #endif result = __Pyx_PyObject_GetAttrStr(obj, attr_name); if (unlikely(!result)) { __Pyx_PyObject_GetAttrStr_ClearAttributeError(); } return result; } /* SetupReduce */ static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { int ret; PyObject *name_attr; name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); if (likely(name_attr)) { ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); } else { ret = -1; } if (unlikely(ret < 0)) { PyErr_Clear(); ret = 0; } Py_XDECREF(name_attr); return ret; } static int __Pyx_setup_reduce(PyObject* type_obj) { int ret = 0; PyObject *object_reduce = NULL; PyObject *object_reduce_ex = NULL; PyObject *reduce = NULL; PyObject *reduce_ex = NULL; PyObject *reduce_cython = NULL; PyObject *setstate = NULL; PyObject *setstate_cython = NULL; #if CYTHON_USE_PYTYPE_LOOKUP if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; #else if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; #endif #if CYTHON_USE_PYTYPE_LOOKUP object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #else object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #endif reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; if (reduce_ex == object_reduce_ex) { #if CYTHON_USE_PYTYPE_LOOKUP object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; #else object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; #endif reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); if (likely(reduce_cython)) { ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (reduce == object_reduce || PyErr_Occurred()) { goto __PYX_BAD; } setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); if (!setstate) PyErr_Clear(); if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); if (likely(setstate_cython)) { ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (!setstate || PyErr_Occurred()) { goto __PYX_BAD; } } PyType_Modified((PyTypeObject*)type_obj); } } goto __PYX_GOOD; __PYX_BAD: if (!PyErr_Occurred()) PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); ret = -1; __PYX_GOOD: #if !CYTHON_USE_PYTYPE_LOOKUP Py_XDECREF(object_reduce); Py_XDECREF(object_reduce_ex); #endif Py_XDECREF(reduce); Py_XDECREF(reduce_ex); Py_XDECREF(reduce_cython); Py_XDECREF(setstate); Py_XDECREF(setstate_cython); return ret; } /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size) { PyObject *result = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif result = PyObject_GetAttrString(module, class_name); 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 ((size_t)basicsize < size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(result); return NULL; } #endif /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif if (unlikely(!__pyx_cython_runtime)) { return c_line; } __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); if (likely(cython_runtime_dict)) { __PYX_PY_DICT_LOOKUP_IF_MODIFIED( use_cline, *cython_runtime_dict, __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ 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 - start) / 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); } /* AddTraceback */ #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; PyThreadState *tstate = __Pyx_PyThreadState_Current; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } 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( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #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 (__Pyx_TypeCheck(obj, __pyx_ptype_7cpython_5array_array)) return __pyx_pw_7cpython_5array_5array_1__getbuffer__(obj, view, flags); if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); if (__Pyx_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 ((0)) {} else if (__Pyx_TypeCheck(obj, __pyx_ptype_7cpython_5array_array)) __pyx_pw_7cpython_5array_5array_3__releasebuffer__(obj, view); view->obj = NULL; Py_DECREF(obj); } #endif /* MemviewSliceIsContig */ 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; } /* OverlappingSlices */ 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); } /* Capsule */ 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; } /* IsLittleEndian */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) { union { uint32_t u32; uint8_t u8[4]; } S; S.u32 = 0x01020304; return S.u8[0] == 4; } /* BufferFormatCheck */ 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 '?': return "'bool'"; 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 '?': 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 '?': 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 PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number, 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; ndim = ctx->head->field->type->ndim; 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_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_Is_Little_Endian()) { 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; } CYTHON_FALLTHROUGH; case '?': 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->is_valid_array)) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } CYTHON_FALLTHROUGH; 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; } } } } /* TypeInfoCompare */ 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; } /* MemviewSliceValidateAndInit */ 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 (unlikely(buf->strides[dim] != sizeof(void *))) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly contiguous " "in dimension %d.", dim); goto fail; } } else if (unlikely(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 (unlikely(stride < buf->itemsize)) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } } else { if (unlikely(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 (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not indirect in " "dimension %d", dim); goto fail; } else if (unlikely(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 (unlikely(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 (unlikely(!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 (unlikely(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 (unlikely(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 (unlikely(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 (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; } if (unlikely((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; } if (buf->len > 0) { for (i = 0; i < ndim; i++) { spec = axes_specs[i]; if (unlikely(!__pyx_check_strides(buf, i, ndim, spec))) goto fail; if (unlikely(!__pyx_check_suboffsets(buf, i, ndim, spec))) goto fail; } if (unlikely(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; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dcd__double(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_F_CONTIG, (PyBUF_F_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 2, &__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; } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ 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 (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj, int writable_flag) { __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_RO | writable_flag, 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; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj, int writable_flag) { __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_RO | writable_flag, 1, &__Pyx_TypeInfo_int, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dcd__double__const__(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_F_CONTIG, (PyBUF_F_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 2, &__Pyx_TypeInfo_double__const__, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int__const__(PyObject *obj, int writable_flag) { __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_RO | writable_flag, 1, &__Pyx_TypeInfo_int__const__, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* MemviewDtypeToObject */ static CYTHON_INLINE PyObject *__pyx_memview_get_int(const char *itemp) { return (PyObject *) __Pyx_PyInt_From_int(*(int *) itemp); } static CYTHON_INLINE int __pyx_memview_set_int(const char *itemp, PyObject *obj) { int value = __Pyx_PyInt_As_int(obj); if ((value == (int)-1) && PyErr_Occurred()) return 0; *(int *) itemp = value; return 1; } /* MemviewDtypeToObject */ static CYTHON_INLINE PyObject *__pyx_memview_get_double(const char *itemp) { return (PyObject *) PyFloat_FromDouble(*(double *) itemp); } static CYTHON_INLINE int __pyx_memview_set_double(const char *itemp, PyObject *obj) { double value = __pyx_PyFloat_AsDouble(obj); if ((value == (double)-1) && PyErr_Occurred()) return 0; *(double *) itemp = value; return 1; } /* MemviewDtypeToObject */ static CYTHON_INLINE PyObject *__pyx_memview_get_int__const__(const char *itemp) { return (PyObject *) __Pyx_PyInt_From_int(*(int const *) itemp); } /* Declarations */ #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 /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_float(__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_sum_float(__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_diff_float(__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_prod_float(__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; } #if 1 static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabsf(b.real) >= fabsf(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { float r = b.imag / b.real; float s = (float)(1.0) / (b.real + b.imag * r); return __pyx_t_float_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { float r = b.real / b.imag; float s = (float)(1.0) / (b.imag + b.real * r); return __pyx_t_float_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else { float denom = b.real * b.real + b.imag * b.imag; return __pyx_t_float_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__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_zero_float(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__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_abs_float(__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_pow_float(__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: return __Pyx_c_prod_float(a, a); case 3: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, a); case 4: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = powf(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2f(0.0, -1.0); } } else { r = __Pyx_c_abs_float(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 /* Declarations */ #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 /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_double(__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_double(__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_double(__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_double(__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; } #if 1 static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabs(b.real) >= fabs(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { double r = b.imag / b.real; double s = (double)(1.0) / (b.real + b.imag * r); return __pyx_t_double_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { double r = b.real / b.imag; double s = (double)(1.0) / (b.imag + b.real * r); return __pyx_t_double_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else { double denom = b.real * b.real + b.imag * b.imag; return __pyx_t_double_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__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_double(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__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_double(__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_double(__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: return __Pyx_c_prod_double(a, a); case 3: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, a); case 4: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = pow(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2(0.0, -1.0); } } else { r = __Pyx_c_abs_double(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 /* MemviewSliceCopyTemplate */ 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 (unlikely(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; } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const int neg_one = (int) -1, const_zero = (int) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif 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_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #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_IntOrLong(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_IntOrLong(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; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const int neg_one = (int) -1, const_zero = (int) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif 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); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const long neg_one = (long) -1, const_zero = (long) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif 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); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const long neg_one = (long) -1, const_zero = (long) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif 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_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #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_IntOrLong(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_IntOrLong(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; } /* CIntFromPy */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const char neg_one = (char) -1, const_zero = (char) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif 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_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (char) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(char) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) case -2: if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -3: if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -4: if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; } #endif if (sizeof(char) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #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_IntOrLong(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_IntOrLong(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; } /* CheckBinaryVersion */ 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; } /* FunctionImport */ #ifndef __PYX_HAVE_RT_ImportFunction #define __PYX_HAVE_RT_ImportFunction static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { PyObject *d = 0; PyObject *cobj = 0; union { void (*fp)(void); void *p; } tmp; d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); if (!d) goto bad; cobj = PyDict_GetItemString(d, funcname); if (!cobj) { PyErr_Format(PyExc_ImportError, "%.200s does not export expected C function %.200s", PyModule_GetName(module), funcname); goto bad; } #if PY_VERSION_HEX >= 0x02070000 if (!PyCapsule_IsValid(cobj, sig)) { PyErr_Format(PyExc_TypeError, "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); goto bad; } tmp.p = PyCapsule_GetPointer(cobj, sig); #else {const char *desc, *s1, *s2; desc = (const char *)PyCObject_GetDesc(cobj); if (!desc) goto bad; s1 = desc; s2 = sig; while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } if (*s1 != *s2) { PyErr_Format(PyExc_TypeError, "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", PyModule_GetName(module), funcname, sig, desc); goto bad; } tmp.p = PyCObject_AsVoidPtr(cobj);} #endif *f = tmp.fp; if (!(*f)) goto bad; Py_DECREF(d); return 0; bad: Py_XDECREF(d); return -1; } #endif /* InitStrings */ 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; if (PyObject_Hash(*t->p) == -1) 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 const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { 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 static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(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 #endif static CYTHON_INLINE const 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)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) 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 int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; retval = __Pyx_PyObject_IsTrue(x); Py_DECREF(x); return retval; } static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", Py_TYPE(result)->tp_name)) { Py_DECREF(result); return NULL; } return result; } #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", type_name, type_name, Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) #else if (likely(PyLong_Check(x))) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; res = m->nb_long(x); } #else if (likely(m && m->nb_int)) { name = "int"; res = m->nb_int(x); } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } #endif if (likely(res)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else if (unlikely(!PyLong_CheckExact(res))) { #endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } 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))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #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_PyBool_FromLong(long b) { return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
mxnet_op.h
#include "hip/hip_runtime.h" /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file mxnet_op.h * \brief * \author Junyuan Xie */ #ifndef MXNET_OPERATOR_MXNET_OP_H_ #define MXNET_OPERATOR_MXNET_OP_H_ #include <dmlc/omp.h> #include <mxnet/base.h> #include <mxnet/engine.h> #include <mxnet/op_attr_types.h> #include <algorithm> #include "./operator_tune.h" #include "../engine/openmp.h" #ifdef __HIPCC__ #include "../common/cuda_utils.h" #endif // __HIPCC__ namespace mxnet { namespace op { namespace mxnet_op { using namespace mshadow; #if __HIP_DEVICE_COMPILE__ __constant__ const float PI = 3.14159265358979323846; #else const float PI = 3.14159265358979323846; using std::isnan; #endif template<typename xpu> int get_num_threads(const int N); #ifdef __HIPCC__ #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) inline hipDeviceProp_t cuda_get_device_prop() { int device; CUDA_CALL(hipGetDevice(&device)); hipDeviceProp_t deviceProp; CUDA_CALL(hipGetDeviceProperties(&deviceProp, device)); return deviceProp; } /*! * \brief Get the number of blocks for cuda kernel given N */ inline int cuda_get_num_blocks(const int N) { using namespace mshadow::cuda; return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); } template<> inline int get_num_threads<gpu>(const int N) { using namespace mshadow::cuda; return kBaseThreadNum * cuda_get_num_blocks(N); } #endif // __HIPCC__ template<> inline int get_num_threads<cpu>(const int N) { return engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); } /*! \brief operator request type switch */ #define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } /*! \brief operator request type switch */ #define MXNET_REQ_TYPE_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ { \ const OpReqType ReqType = kNullOp; \ {__VA_ARGS__} \ } \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } #define MXNET_NDIM_SWITCH(NDim, ndim, ...) \ if (NDim == 0) { \ } else if (NDim == 1) { \ const int ndim = 1; \ {__VA_ARGS__} \ } else if (NDim == 2) { \ const int ndim = 2; \ {__VA_ARGS__} \ } else if (NDim == 3) { \ const int ndim = 3; \ {__VA_ARGS__} \ } else if (NDim == 4) { \ const int ndim = 4; \ {__VA_ARGS__} \ } else if (NDim == 5) { \ const int ndim = 5; \ {__VA_ARGS__} \ } else { \ LOG(FATAL) << "ndim=" << NDim << "too large "; \ } #define MXNET_NO_INT8_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_NO_FLOAT16_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ LOG(FATAL) << "This operation does not " \ "support float16"; \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } /*! * \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 int ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { int ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i]; } return ret; } /* Compute coordinates from flattened index given shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> unravel(const int idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (int i = ndim-1, j = idx; i >=0; --i) { int tmp = j / shape[i]; ret[i] = j - tmp*shape[i]; j = tmp; } return ret; } /* Compute dot product of two vector */ template<int ndim> MSHADOW_XINLINE int dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { int ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret += coord[i] * stride[i]; } return ret; } /* Combining unravel and dot */ template<int ndim> MSHADOW_XINLINE int unravel_dot(const int idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { int ret = 0; #pragma unroll for (int i = ndim-1, j = idx; i >=0; --i) { int tmp = j / shape[i]; ret += (j - tmp*shape[i])*stride[i]; j = tmp; } return ret; } /* Calculate stride of each dim from shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) { Shape<ndim> stride; index_t cumprod = 1; #pragma unroll for (int i = ndim - 1; i >= 0; --i) { stride[i] = (shape[i] > 1) ? cumprod : 0; cumprod *= shape[i]; } return stride; } /* 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(int i, DType *out, const DType *in) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i])); } /*! \brief inputs are two tensors */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is tensor and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } /*! \brief input is tensor and two scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int 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(int i, DType *out) { KERNEL_ASSIGN(out[i], req, OP::Map()); } /*! \brief input is single scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(value)); } /*! \brief inputs are two tensors and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *input_1, const DType *input_2, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value)); } /*! \brief inputs are three tensors (ie backward grad with binary grad function) */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *input_1, const DType *input_2, const DType *input_3) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i])); } }; 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 int N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { for (int i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int 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 int N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2 || !tuned_op<PRIMITIVE_OP, DType>::UseOMP( static_cast<size_t>(N), static_cast<size_t>(omp_threads))) { for (int i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int 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 int N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { OP::Map(0, N, args...); } else { const int length = (N + omp_threads - 1) / omp_threads; #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 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 int 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 int N, DType *dest, Args... args) { LaunchTuned<typename T::Operation, DType>(s, N, dest, args...); return true; } }; #ifdef __HIPCC__ template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, args...); } } template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel_ex(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, 1, args...); } } template<typename OP> struct Kernel<OP, gpu> { /*! \brief Launch GPU kernel */ template<typename ...Args> inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) { using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); hipLaunchKernelGGL(HIP_KERNEL_NAME(mxnet_generic_kernel<OP, Args...>), dim3(ngrid), dim3(kBaseThreadNum), 0, mshadow::Stream<gpu>::GetStream(s), N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel); } template<typename ...Args> inline static void LaunchEx(mshadow::Stream<gpu> *s, const int N, Args... args) { using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); hipLaunchKernelGGL(HIP_KERNEL_NAME(mxnet_generic_kernel_ex<OP, Args...>), dim3(ngrid), dim3(kBaseThreadNum), 0, mshadow::Stream<gpu>::GetStream(s), N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel_ex); } }; #endif // __HIPCC__ /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<int val> struct set_to_int : public tunable { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out) { out[i] = DType(val); } // mshadow_op version (when used with op_with_req<>) MSHADOW_XINLINE static int Map() { return val; } }; /*! * \brief Special-case kernel shortcut for setting to zero 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_
visual-effects.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF X X % % F X X % % FFF X % % F X X % % F X X % % % % % % MagickCore Image Special Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/transform.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" #include "MagickCore/visual-effects.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d d N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddNoiseImage() adds random noise to the image. % % The format of the AddNoiseImage method is: % % Image *AddNoiseImage(const Image *image,const NoiseType noise_type, % const double attenuate,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o noise_type: The type of noise: Uniform, Gaussian, Multiplicative, % Impulse, Laplacian, or Poisson. % % o attenuate: attenuate the random distribution. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type, const double attenuate,ExceptionInfo *exception) { #define AddNoiseImageTag "AddNoise/Image" CacheView *image_view, *noise_view; Image *noise_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize noise image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateAddNoiseImage(image,noise_type,attenuate,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } /* Add noise in each row. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,noise_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel); if ((traits == UndefinedPixelTrait) || (noise_traits == UndefinedPixelTrait)) continue; if ((noise_traits & CopyPixelTrait) != 0) { SetPixelChannel(noise_image,channel,p[i],q); continue; } SetPixelChannel(noise_image,channel,ClampToQuantum( GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)), q); } p+=GetPixelChannels(image); q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AddNoiseImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u e S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlueShiftImage() mutes the colors of the image to simulate a scene at % nighttime in the moonlight. % % The format of the BlueShiftImage method is: % % Image *BlueShiftImage(const Image *image,const double factor, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o factor: the shift factor. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlueShiftImage(const Image *image,const double factor, ExceptionInfo *exception) { #define BlueShiftImageTag "BlueShift/Image" CacheView *image_view, *shift_view; Image *shift_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate blue shift image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); shift_image=CloneImage(image,0,0,MagickTrue,exception); if (shift_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse) { shift_image=DestroyImage(shift_image); return((Image *) NULL); } /* Blue-shift DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); shift_view=AcquireAuthenticCacheView(shift_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,shift_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; Quantum quantum; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) < quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) < quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum); pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum); pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum); quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) > quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) > quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(pixel.red+factor*quantum); pixel.green=0.5*(pixel.green+factor*quantum); pixel.blue=0.5*(pixel.blue+factor*quantum); SetPixelRed(shift_image,ClampToQuantum(pixel.red),q); SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q); SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q); p+=GetPixelChannels(image); q+=GetPixelChannels(shift_image); } sync=SyncCacheViewAuthenticPixels(shift_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlueShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shift_view=DestroyCacheView(shift_view); if (status == MagickFalse) shift_image=DestroyImage(shift_image); return(shift_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a r c o a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CharcoalImage() creates a new image that is a copy of an existing one with % the edge highlighted. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the CharcoalImage method is: % % Image *CharcoalImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CharcoalImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *charcoal_image, *edge_image; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) return((Image *) NULL); edge_image->alpha_trait=UndefinedPixelTrait; charcoal_image=(Image *) NULL; status=ClampImage(edge_image,exception); if (status != MagickFalse) charcoal_image=BlurImage(edge_image,radius,sigma,exception); edge_image=DestroyImage(edge_image); if (charcoal_image == (Image *) NULL) return((Image *) NULL); status=NormalizeImage(charcoal_image,exception); if (status != MagickFalse) status=NegateImage(charcoal_image,MagickFalse,exception); if (status != MagickFalse) status=GrayscaleImage(charcoal_image,image->intensity,exception); if (status == MagickFalse) charcoal_image=DestroyImage(charcoal_image); return(charcoal_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorizeImage() blends the fill color with each pixel in the image. % A percentage blend is specified with opacity. Control the application % of different color components by specifying a different percentage for % each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue). % % The format of the ColorizeImage method is: % % Image *ColorizeImage(const Image *image,const char *blend, % const PixelInfo *colorize,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A character string indicating the level of blending as a % percentage. % % o colorize: A color value. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorizeImage(const Image *image,const char *blend, const PixelInfo *colorize,ExceptionInfo *exception) { #define ColorizeImageTag "Colorize/Image" #define Colorize(pixel,blend_percentage,colorize) \ (((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0) CacheView *image_view; GeometryInfo geometry_info; Image *colorize_image; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; PixelInfo blend_percentage; ssize_t y; /* Allocate colorized image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); colorize_image=CloneImage(image,0,0,MagickTrue,exception); if (colorize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse) { colorize_image=DestroyImage(colorize_image); return((Image *) NULL); } if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) || (IsPixelInfoGray(colorize) != MagickFalse)) (void) SetImageColorspace(colorize_image,sRGBColorspace,exception); if ((colorize_image->alpha_trait == UndefinedPixelTrait) && (colorize->alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(colorize_image,OpaqueAlpha,exception); if (blend == (const char *) NULL) return(colorize_image); GetPixelInfo(colorize_image,&blend_percentage); flags=ParseGeometry(blend,&geometry_info); blend_percentage.red=geometry_info.rho; blend_percentage.green=geometry_info.rho; blend_percentage.blue=geometry_info.rho; blend_percentage.black=geometry_info.rho; blend_percentage.alpha=(MagickRealType) TransparentAlpha; if ((flags & SigmaValue) != 0) blend_percentage.green=geometry_info.sigma; if ((flags & XiValue) != 0) blend_percentage.blue=geometry_info.xi; if ((flags & PsiValue) != 0) blend_percentage.alpha=geometry_info.psi; if (blend_percentage.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) blend_percentage.black=geometry_info.psi; if ((flags & ChiValue) != 0) blend_percentage.alpha=geometry_info.chi; } /* Colorize DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(colorize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(colorize_image,colorize_image,colorize_image->rows,1) #endif for (y=0; y < (ssize_t) colorize_image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) colorize_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++) { PixelTrait traits = GetPixelChannelTraits(colorize_image, (PixelChannel) i); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum( Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i), GetPixelInfoChannel(colorize,(PixelChannel) i))),q); } q+=GetPixelChannels(colorize_image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorizeImageTag,progress, colorize_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) colorize_image=DestroyImage(colorize_image); return(colorize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r M a t r i x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorMatrixImage() applies color transformation to an image. This method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the ColorMatrixImage method is: % % Image *ColorMatrixImage(const Image *image, % const KernelInfo *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_matrix: the color matrix. % % o exception: return any errors or warnings in this structure. % */ /* FUTURE: modify to make use of a MagickMatrix Mutliply function That should be provided in "matrix.c" (ASIDE: actually distorts should do this too but currently doesn't) */ MagickExport Image *ColorMatrixImage(const Image *image, const KernelInfo *color_matrix,ExceptionInfo *exception) { #define ColorMatrixImageTag "ColorMatrix/Image" CacheView *color_view, *image_view; double ColorMatrix[6][6] = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 } }; Image *color_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t u, v, y; /* Map given color_matrix, into a 6x6 matrix RGBKA and a constant */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=0; for (v=0; v < (ssize_t) color_matrix->height; v++) for (u=0; u < (ssize_t) color_matrix->width; u++) { if ((v < 6) && (u < 6)) ColorMatrix[v][u]=color_matrix->values[i]; i++; } /* Initialize color image. */ color_image=CloneImage(image,0,0,MagickTrue,exception); if (color_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse) { color_image=DestroyImage(color_image); return((Image *) NULL); } if (image->debug != MagickFalse) { char format[MagickPathExtent], *message; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " ColorMatrix image with color matrix:"); message=AcquireString(""); for (v=0; v < 6; v++) { *message='\0'; (void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < 6; u++) { (void) FormatLocaleString(format,MagickPathExtent,"%+f ", ColorMatrix[v][u]); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } /* Apply the ColorMatrix to image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); color_view=AcquireAuthenticCacheView(color_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,color_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t v; size_t height; GetPixelInfoPixel(image,p,&pixel); height=color_matrix->height > 6 ? 6UL : color_matrix->height; for (v=0; v < (ssize_t) height; v++) { double sum; sum=ColorMatrix[v][0]*GetPixelRed(image,p)+ColorMatrix[v][1]* GetPixelGreen(image,p)+ColorMatrix[v][2]*GetPixelBlue(image,p); if (image->colorspace == CMYKColorspace) sum+=ColorMatrix[v][3]*GetPixelBlack(image,p); if (image->alpha_trait != UndefinedPixelTrait) sum+=ColorMatrix[v][4]*GetPixelAlpha(image,p); sum+=QuantumRange*ColorMatrix[v][5]; switch (v) { case 0: pixel.red=sum; break; case 1: pixel.green=sum; break; case 2: pixel.blue=sum; break; case 3: pixel.black=sum; break; case 4: pixel.alpha=sum; break; default: break; } } SetPixelViaPixelInfo(color_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(color_image); } if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorMatrixImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } color_view=DestroyCacheView(color_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) color_image=DestroyImage(color_image); return(color_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p l o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImplodeImage() creates a new image that is a copy of an existing % one with the image pixels "implode" by the specified percentage. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ImplodeImage method is: % % Image *ImplodeImage(const Image *image,const double amount, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o implode_image: Method ImplodeImage returns a pointer to the image % after it is implode. A null image is returned if there is a memory % shortage. % % o image: the image. % % o amount: Define the extent of the implosion. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ImplodeImage(const Image *image,const double amount, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ImplodeImageTag "Implode/Image" CacheView *canvas_view, *implode_view, *interpolate_view; double radius; Image *canvas_image, *implode_image; MagickBooleanType status; MagickOffsetType progress; PointInfo center, scale; ssize_t y; /* Initialize implode image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlphaChannel(canvas_image,OpaqueAlphaChannel,exception); implode_image=CloneImage(canvas_image,0,0,MagickTrue,exception); if (implode_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); implode_image=DestroyImage(implode_image); return((Image *) NULL); } /* Compute scaling factor. */ scale.x=1.0; scale.y=1.0; center.x=0.5*canvas_image->columns; center.y=0.5*canvas_image->rows; radius=center.x; if (canvas_image->columns > canvas_image->rows) scale.y=(double) canvas_image->columns/(double) canvas_image->rows; else if (canvas_image->columns < canvas_image->rows) { scale.x=(double) canvas_image->rows/(double) canvas_image->columns; radius=center.y; } /* Implode image. */ status=MagickTrue; progress=0; canvas_view=AcquireVirtualCacheView(canvas_image,exception); interpolate_view=AcquireVirtualCacheView(canvas_image,exception); implode_view=AcquireAuthenticCacheView(implode_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,implode_image,canvas_image->rows,1) #endif for (y=0; y < (ssize_t) canvas_image->rows; y++) { double distance; PointInfo delta; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) canvas_image->columns; x++) { register ssize_t i; /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++) { PixelChannel channel = GetPixelChannelChannel(canvas_image,i); PixelTrait traits = GetPixelChannelTraits(canvas_image,channel); PixelTrait implode_traits = GetPixelChannelTraits(implode_image, channel); if ((traits == UndefinedPixelTrait) || (implode_traits == UndefinedPixelTrait)) continue; SetPixelChannel(implode_image,channel,p[i],q); } else { double factor; /* Implode the pixel. */ factor=1.0; if (distance > 0.0) factor=pow(sin(MagickPI*sqrt((double) distance)/radius/2),-amount); status=InterpolatePixelChannels(canvas_image,interpolate_view, implode_image,method,(double) (factor*delta.x/scale.x+center.x), (double) (factor*delta.y/scale.y+center.y),q,exception); if (status == MagickFalse) break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(implode_image); } if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse) status=MagickFalse; if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,ImplodeImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } implode_view=DestroyCacheView(implode_view); interpolate_view=DestroyCacheView(interpolate_view); canvas_view=DestroyCacheView(canvas_view); canvas_image=DestroyImage(canvas_image); if (status == MagickFalse) implode_image=DestroyImage(implode_image); return(implode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The MorphImages() method requires a minimum of two images. The first % image is transformed into the second by a number of intervening images % as specified by frames. % % The format of the MorphImage method is: % % Image *MorphImages(const Image *image,const size_t number_frames, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_frames: Define the number of in-between image to generate. % The more in-between frames, the smoother the morph. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphImages(const Image *image,const size_t number_frames, ExceptionInfo *exception) { #define MorphImageTag "Morph/Image" double alpha, beta; Image *morph_image, *morph_images; MagickBooleanType status; MagickOffsetType scene; register const Image *next; register ssize_t n; ssize_t y; /* Clone first frame in sequence. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); morph_images=CloneImage(image,0,0,MagickTrue,exception); if (morph_images == (Image *) NULL) return((Image *) NULL); if (GetNextImageInList(image) == (Image *) NULL) { /* Morph single image. */ for (n=1; n < (ssize_t) number_frames; n++) { morph_image=CloneImage(image,0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n, number_frames); if (proceed == MagickFalse) status=MagickFalse; } } return(GetFirstImageInList(morph_images)); } /* Morph image sequence. */ status=MagickTrue; scene=0; next=image; for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next)) { for (n=0; n < (ssize_t) number_frames; n++) { CacheView *image_view, *morph_view; beta=(double) (n+1.0)/(double) (number_frames+1.0); alpha=1.0-beta; morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta* GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta* GetNextImageInList(next)->rows+0.5),next->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } status=SetImageStorageClass(morph_image,DirectClass,exception); if (status == MagickFalse) { morph_image=DestroyImage(morph_image); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns, morph_images->rows,GetNextImageInList(next)->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } image_view=AcquireVirtualCacheView(morph_image,exception); morph_view=AcquireAuthenticCacheView(morph_images,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(morph_image,morph_image,morph_image->rows,1) #endif for (y=0; y < (ssize_t) morph_images->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1, exception); q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) morph_images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++) { PixelChannel channel = GetPixelChannelChannel(morph_image,i); PixelTrait traits = GetPixelChannelTraits(morph_image,channel); PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel); if ((traits == UndefinedPixelTrait) || (morph_traits == UndefinedPixelTrait)) continue; if ((morph_traits & CopyPixelTrait) != 0) { SetPixelChannel(morph_image,channel,p[i],q); continue; } SetPixelChannel(morph_image,channel,ClampToQuantum(alpha* GetPixelChannel(morph_images,channel,q)+beta*p[i]),q); } p+=GetPixelChannels(morph_image); q+=GetPixelChannels(morph_images); } sync=SyncCacheViewAuthenticPixels(morph_view,exception); if (sync == MagickFalse) status=MagickFalse; } morph_view=DestroyCacheView(morph_view); image_view=DestroyCacheView(image_view); morph_image=DestroyImage(morph_image); } if (n < (ssize_t) number_frames) break; /* Clone last frame in sequence. */ morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,scene, GetImageListLength(image)); if (proceed == MagickFalse) status=MagickFalse; } scene++; } if (GetNextImageInList(next) != (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } return(GetFirstImageInList(morph_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P l a s m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PlasmaImage() initializes an image with plasma fractal values. The image % must be initialized with a base color and the random number generator % seeded before this method is called. % % The format of the PlasmaImage method is: % % MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment, % size_t attenuate,size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o segment: Define the region to apply plasma fractals values. % % o attenuate: Define the plasma attenuation factor. % % o depth: Limit the plasma recursion depth. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PlasmaPixel(RandomInfo *magick_restrict random_info, const double pixel,const double noise) { MagickRealType plasma; plasma=pixel+noise*GetPseudoRandomValue(random_info)-noise/2.0; return(ClampToQuantum(plasma)); } static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view, CacheView *u_view,CacheView *v_view,RandomInfo *magick_restrict random_info, const SegmentInfo *magick_restrict segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { double plasma; MagickStatusType status; register const Quantum *magick_restrict u, *magick_restrict v; register Quantum *magick_restrict q; register ssize_t i; ssize_t x, x_mid, y, y_mid; if ((fabs(segment->x2-segment->x1) < MagickEpsilon) && (fabs(segment->y2-segment->y1) < MagickEpsilon)) return(MagickTrue); if (depth != 0) { SegmentInfo local_info; /* Divide the area into quadrants and recurse. */ depth--; attenuate++; x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); local_info=(*segment); local_info.x2=(double) x_mid; local_info.y2=(double) y_mid; status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.y1=(double) y_mid; local_info.x2=(double) x_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y2=(double) y_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y1=(double) y_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); return(status == 0 ? MagickFalse : MagickTrue); } x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); if ((fabs(segment->x1-x_mid) < MagickEpsilon) && (fabs(segment->x2-x_mid) < MagickEpsilon) && (fabs(segment->y1-y_mid) < MagickEpsilon) && (fabs(segment->y2-y_mid) < MagickEpsilon)) return(MagickFalse); /* Average pixels and apply plasma. */ status=MagickTrue; plasma=(double) QuantumRange/(2.0*attenuate); if ((fabs(segment->x1-x_mid) >= MagickEpsilon) || (fabs(segment->x2-x_mid) >= MagickEpsilon)) { /* Left pixel. */ x=(ssize_t) ceil(segment->x1-0.5); u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),1,1, exception); v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),1,1, exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); if (fabs(segment->x1-segment->x2) >= MagickEpsilon) { /* Right pixel. */ x=(ssize_t) ceil(segment->x2-0.5); u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5), 1,1,exception); v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5), 1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->y1-y_mid) >= MagickEpsilon) || (fabs(segment->y2-y_mid) >= MagickEpsilon)) { if ((fabs(segment->x1-x_mid) >= MagickEpsilon) || (fabs(segment->y2-y_mid) >= MagickEpsilon)) { /* Bottom pixel. */ y=(ssize_t) ceil(segment->y2-0.5); u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y, 1,1,exception); v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y, 1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } if (fabs(segment->y1-segment->y2) >= MagickEpsilon) { /* Top pixel. */ y=(ssize_t) ceil(segment->y1-0.5); u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y, 1,1,exception); v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y, 1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->x1-segment->x2) >= MagickEpsilon) || (fabs(segment->y1-segment->y2) >= MagickEpsilon)) { /* Middle pixel. */ x=(ssize_t) ceil(segment->x1-0.5); y=(ssize_t) ceil(segment->y1-0.5); u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception); x=(ssize_t) ceil(segment->x2-0.5); y=(ssize_t) ceil(segment->y2-0.5); v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } if ((fabs(segment->x2-segment->x1) < 3.0) && (fabs(segment->y2-segment->y1) < 3.0)) return(status == 0 ? MagickFalse : MagickTrue); return(MagickFalse); } MagickExport MagickBooleanType PlasmaImage(Image *image, const SegmentInfo *segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { CacheView *image_view, *u_view, *v_view; MagickBooleanType status; RandomInfo *random_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); u_view=AcquireVirtualCacheView(image,exception); v_view=AcquireVirtualCacheView(image,exception); random_info=AcquireRandomInfo(); status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment, attenuate,depth,exception); random_info=DestroyRandomInfo(random_info); v_view=DestroyCacheView(v_view); u_view=DestroyCacheView(u_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l a r o i d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolaroidImage() simulates a Polaroid picture. % % The format of the PolaroidImage method is: % % Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, % const char *caption,const double angle, % const PixelInterpolateMethod method,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o caption: the Polaroid caption. % % o angle: Apply the effect along this angle. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, const char *caption,const double angle,const PixelInterpolateMethod method, ExceptionInfo *exception) { Image *bend_image, *caption_image, *flop_image, *picture_image, *polaroid_image, *rotate_image, *trim_image; size_t height; ssize_t quantum; /* Simulate a Polaroid picture. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double) image->rows)/25.0,10.0); height=image->rows+2*quantum; caption_image=(Image *) NULL; if (caption != (const char *) NULL) { char *text; /* Generate caption image. */ caption_image=CloneImage(image,image->columns,1,MagickTrue,exception); if (caption_image == (Image *) NULL) return((Image *) NULL); text=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,caption, exception); if (text != (char *) NULL) { char geometry[MagickPathExtent]; DrawInfo *annotate_info; MagickBooleanType status; ssize_t count; TypeMetric metrics; annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info); (void) CloneString(&annotate_info->text,text); count=FormatMagickCaption(caption_image,annotate_info,MagickTrue, &metrics,&text,exception); status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)*(metrics.ascent-metrics.descent)+0.5),exception); if (status == MagickFalse) caption_image=DestroyImage(caption_image); else { caption_image->background_color=image->border_color; (void) SetImageBackgroundColor(caption_image,exception); (void) CloneString(&annotate_info->text,text); (void) FormatLocaleString(geometry,MagickPathExtent,"+0+%.20g", metrics.ascent); if (annotate_info->gravity == UndefinedGravity) (void) CloneString(&annotate_info->geometry,AcquireString( geometry)); (void) AnnotateImage(caption_image,annotate_info,exception); height+=caption_image->rows; } annotate_info=DestroyDrawInfo(annotate_info); text=DestroyString(text); } } picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue, exception); if (picture_image == (Image *) NULL) { if (caption_image != (Image *) NULL) caption_image=DestroyImage(caption_image); return((Image *) NULL); } picture_image->background_color=image->border_color; (void) SetImageBackgroundColor(picture_image,exception); (void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum, quantum,exception); if (caption_image != (Image *) NULL) { (void) CompositeImage(picture_image,caption_image,OverCompositeOp, MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception); caption_image=DestroyImage(caption_image); } (void) QueryColorCompliance("none",AllCompliance, &picture_image->background_color,exception); (void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception); rotate_image=RotateImage(picture_image,90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0* picture_image->columns,method,exception); picture_image=DestroyImage(picture_image); if (bend_image == (Image *) NULL) return((Image *) NULL); picture_image=bend_image; rotate_image=RotateImage(picture_image,-90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; picture_image->background_color=image->background_color; polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3, exception); if (polaroid_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } flop_image=FlopImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (flop_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } polaroid_image=flop_image; (void) CompositeImage(polaroid_image,picture_image,OverCompositeOp, MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception); picture_image=DestroyImage(picture_image); (void) QueryColorCompliance("none",AllCompliance, &polaroid_image->background_color,exception); rotate_image=RotateImage(polaroid_image,angle,exception); polaroid_image=DestroyImage(polaroid_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); polaroid_image=rotate_image; trim_image=TrimImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (trim_image == (Image *) NULL) return((Image *) NULL); polaroid_image=trim_image; return(polaroid_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e p i a T o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSepiaToneImage() applies a special effect to the image, similar to the % effect achieved in a photo darkroom by sepia toning. Threshold ranges from % 0 to QuantumRange and is a measure of the extent of the sepia toning. A % threshold of 80% is a good starting point for a reasonable tone. % % The format of the SepiaToneImage method is: % % Image *SepiaToneImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: the tone threshold. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SepiaToneImage(const Image *image,const double threshold, ExceptionInfo *exception) { #define SepiaToneImageTag "SepiaTone/Image" CacheView *image_view, *sepia_view; Image *sepia_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize sepia-toned image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); sepia_image=CloneImage(image,0,0,MagickTrue,exception); if (sepia_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse) { sepia_image=DestroyImage(sepia_image); return((Image *) NULL); } /* Tone each row of the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sepia_view=AcquireAuthenticCacheView(sepia_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,sepia_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double intensity, tone; intensity=GetPixelIntensity(image,p); tone=intensity > threshold ? (double) QuantumRange : intensity+ (double) QuantumRange-threshold; SetPixelRed(sepia_image,ClampToQuantum(tone),q); tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange : intensity+(double) QuantumRange-7.0*threshold/6.0; SetPixelGreen(sepia_image,ClampToQuantum(tone),q); tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0; SetPixelBlue(sepia_image,ClampToQuantum(tone),q); tone=threshold/7.0; if ((double) GetPixelGreen(image,q) < tone) SetPixelGreen(sepia_image,ClampToQuantum(tone),q); if ((double) GetPixelBlue(image,q) < tone) SetPixelBlue(sepia_image,ClampToQuantum(tone),q); SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(sepia_image); } if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SepiaToneImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sepia_view=DestroyCacheView(sepia_view); image_view=DestroyCacheView(image_view); (void) NormalizeImage(sepia_image,exception); (void) ContrastImage(sepia_image,MagickTrue,exception); if (status == MagickFalse) sepia_image=DestroyImage(sepia_image); return(sepia_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d o w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadowImage() simulates a shadow from the specified image and returns it. % % The format of the ShadowImage method is: % % Image *ShadowImage(const Image *image,const double alpha, % const double sigma,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: percentage transparency. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x_offset: the shadow x-offset. % % o y_offset: the shadow y-offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadowImage(const Image *image,const double alpha, const double sigma,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define ShadowImageTag "Shadow/Image" CacheView *image_view; ChannelType channel_mask; Image *border_image, *clone_image, *shadow_image; MagickBooleanType status; PixelInfo background_color; RectangleInfo border_info; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(clone_image,sRGBColorspace,exception); (void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod, exception); border_info.width=(size_t) floor(2.0*sigma+0.5); border_info.height=(size_t) floor(2.0*sigma+0.5); border_info.x=0; border_info.y=0; (void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color, exception); clone_image->alpha_trait=BlendPixelTrait; border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception); clone_image=DestroyImage(clone_image); if (border_image == (Image *) NULL) return((Image *) NULL); if (border_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception); /* Shadow image. */ status=MagickTrue; background_color=border_image->background_color; background_color.alpha_trait=BlendPixelTrait; image_view=AcquireAuthenticCacheView(border_image,exception); for (y=0; y < (ssize_t) border_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) border_image->columns; x++) { if (border_image->alpha_trait != UndefinedPixelTrait) background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0; SetPixelViaPixelInfo(border_image,&background_color,q); q+=GetPixelChannels(border_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { border_image=DestroyImage(border_image); return((Image *) NULL); } channel_mask=SetImageChannelMask(border_image,AlphaChannel); shadow_image=BlurImage(border_image,0.0,sigma,exception); border_image=DestroyImage(border_image); if (shadow_image == (Image *) NULL) return((Image *) NULL); (void) SetPixelChannelMask(shadow_image,channel_mask); if (shadow_image->page.width == 0) shadow_image->page.width=shadow_image->columns; if (shadow_image->page.height == 0) shadow_image->page.height=shadow_image->rows; shadow_image->page.width+=x_offset-(ssize_t) border_info.width; shadow_image->page.height+=y_offset-(ssize_t) border_info.height; shadow_image->page.x+=x_offset-(ssize_t) border_info.width; shadow_image->page.y+=y_offset-(ssize_t) border_info.height; return(shadow_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S k e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SketchImage() simulates a pencil sketch. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SketchImage() selects a suitable radius for you. Angle gives the angle % of the sketch. % % The format of the SketchImage method is: % % Image *SketchImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the % center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SketchImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { CacheView *random_view; Image *blend_image, *blur_image, *dodge_image, *random_image, *sketch_image; MagickBooleanType status; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Sketch image. */ random_image=CloneImage(image,image->columns << 1,image->rows << 1, MagickTrue,exception); if (random_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; random_info=AcquireRandomInfoThreadSet(); random_view=AcquireAuthenticCacheView(random_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) random_image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) random_image->columns; x++) { double value; register ssize_t i; value=GetPseudoRandomValue(random_info[id]); for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=ClampToQuantum(QuantumRange*value); } q+=GetPixelChannels(random_image); } if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse) status=MagickFalse; } random_view=DestroyCacheView(random_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) { random_image=DestroyImage(random_image); return(random_image); } blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception); random_image=DestroyImage(random_image); if (blur_image == (Image *) NULL) return((Image *) NULL); dodge_image=EdgeImage(blur_image,radius,exception); blur_image=DestroyImage(blur_image); if (dodge_image == (Image *) NULL) return((Image *) NULL); status=ClampImage(dodge_image,exception); if (status != MagickFalse) status=NormalizeImage(dodge_image,exception); if (status != MagickFalse) status=NegateImage(dodge_image,MagickFalse,exception); if (status != MagickFalse) status=TransformImage(&dodge_image,(char *) NULL,"50%",exception); sketch_image=CloneImage(image,0,0,MagickTrue,exception); if (sketch_image == (Image *) NULL) { dodge_image=DestroyImage(dodge_image); return((Image *) NULL); } (void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp, MagickTrue,0,0,exception); dodge_image=DestroyImage(dodge_image); blend_image=CloneImage(image,0,0,MagickTrue,exception); if (blend_image == (Image *) NULL) { sketch_image=DestroyImage(sketch_image); return((Image *) NULL); } if (blend_image->alpha_trait != BlendPixelTrait) (void) SetImageAlpha(blend_image,TransparentAlpha,exception); (void) SetImageArtifact(blend_image,"compose:args","20x80"); (void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue, 0,0,exception); blend_image=DestroyImage(blend_image); return(sketch_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o l a r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SolarizeImage() applies a special effect to the image, similar to the effect % achieved in a photo darkroom by selectively exposing areas of photo % sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a % measure of the extent of the solarization. % % The format of the SolarizeImage method is: % % MagickBooleanType SolarizeImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the extent of the solarization. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SolarizeImage(Image *image, const double threshold,ExceptionInfo *exception) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if (image->storage_class == PseudoClass) { register ssize_t i; /* Solarize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((double) image->colormap[i].red > threshold) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((double) image->colormap[i].green > threshold) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((double) image->colormap[i].blue > threshold) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } return(SyncImage(image,exception)); } /* Solarize image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] > threshold) q[i]=QuantumRange-q[i]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e g a n o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SteganoImage() hides a digital watermark within the image. Recover % the hidden watermark later to prove that the authenticity of an image. % Offset defines the start position within the image to hide the watermark. % % The format of the SteganoImage method is: % % Image *SteganoImage(const Image *image,Image *watermark, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o watermark: the watermark image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SteganoImage(const Image *image,const Image *watermark, ExceptionInfo *exception) { #define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0) #define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \ | (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i))) #define SteganoImageTag "Stegano/Image" CacheView *stegano_view, *watermark_view; Image *stegano_image; int c; MagickBooleanType status; PixelInfo pixel; register Quantum *q; register ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize steganographic image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(watermark != (const Image *) NULL); assert(watermark->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1UL; stegano_image=CloneImage(image,0,0,MagickTrue,exception); if (stegano_image == (Image *) NULL) return((Image *) NULL); stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH; if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse) { stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } /* Hide watermark in low-order bits of image. */ c=0; i=0; j=0; depth=stegano_image->depth; k=stegano_image->offset; status=MagickTrue; watermark_view=AcquireVirtualCacheView(watermark,exception); stegano_view=AcquireAuthenticCacheView(stegano_image,exception); for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++) { for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++) { ssize_t offset; (void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel, exception); offset=k/(ssize_t) stegano_image->columns; if (offset >= (ssize_t) stegano_image->rows) break; q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t) stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1, exception); if (q == (Quantum *) NULL) break; switch (c) { case 0: { SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 1: { SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 2: { SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } } if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (stegano_image->columns*stegano_image->columns)) k=0; if (k == stegano_image->offset) j++; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType) (depth-i),depth); if (proceed == MagickFalse) status=MagickFalse; } } stegano_view=DestroyCacheView(stegano_view); watermark_view=DestroyCacheView(watermark_view); if (status == MagickFalse) stegano_image=DestroyImage(stegano_image); return(stegano_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e r e o A n a g l y p h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StereoAnaglyphImage() combines two images and produces a single image that % is the composite of a left and right image of a stereo pair. Special % red-green stereo glasses are required to view this effect. % % The format of the StereoAnaglyphImage method is: % % Image *StereoImage(const Image *left_image,const Image *right_image, % ExceptionInfo *exception) % Image *StereoAnaglyphImage(const Image *left_image, % const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o left_image: the left image. % % o right_image: the right image. % % o exception: return any errors or warnings in this structure. % % o x_offset: amount, in pixels, by which the left image is offset to the % right of the right image. % % o y_offset: amount, in pixels, by which the left image is offset to the % bottom of the right image. % % */ MagickExport Image *StereoImage(const Image *left_image, const Image *right_image,ExceptionInfo *exception) { return(StereoAnaglyphImage(left_image,right_image,0,0,exception)); } MagickExport Image *StereoAnaglyphImage(const Image *left_image, const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define StereoImageTag "Stereo/Image" const Image *image; Image *stereo_image; MagickBooleanType status; ssize_t y; assert(left_image != (const Image *) NULL); assert(left_image->signature == MagickCoreSignature); if (left_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", left_image->filename); assert(right_image != (const Image *) NULL); assert(right_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=left_image; if ((left_image->columns != right_image->columns) || (left_image->rows != right_image->rows)) ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer"); /* Initialize stereo image attributes. */ stereo_image=CloneImage(left_image,left_image->columns,left_image->rows, MagickTrue,exception); if (stereo_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse) { stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } (void) SetImageColorspace(stereo_image,sRGBColorspace,exception); /* Copy left image to red channel and right image to blue channel. */ status=MagickTrue; for (y=0; y < (ssize_t) stereo_image->rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; register Quantum *magick_restrict r; p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1, exception); q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception); r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) || (r == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) stereo_image->columns; x++) { SetPixelRed(stereo_image,GetPixelRed(left_image,p),r); SetPixelGreen(stereo_image,GetPixelGreen(right_image,q),r); SetPixelBlue(stereo_image,GetPixelBlue(right_image,q),r); if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0) SetPixelAlpha(stereo_image,(GetPixelAlpha(left_image,p)+ GetPixelAlpha(right_image,q))/2,r); p+=GetPixelChannels(left_image); q+=GetPixelChannels(right_image); r+=GetPixelChannels(stereo_image); } if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse) break; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y, stereo_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (status == MagickFalse) stereo_image=DestroyImage(stereo_image); return(stereo_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S w i r l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SwirlImage() swirls the pixels about the center of the image, where % degrees indicates the sweep of the arc through which each pixel is moved. % You get a more dramatic effect as the degrees move from 1 to 360. % % The format of the SwirlImage method is: % % Image *SwirlImage(const Image *image,double degrees, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o degrees: Define the tightness of the swirling effect. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SwirlImage(const Image *image,double degrees, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define SwirlImageTag "Swirl/Image" CacheView *canvas_view, *interpolate_view, *swirl_view; double radius; Image *canvas_image, *swirl_image; MagickBooleanType status; MagickOffsetType progress; PointInfo center, scale; ssize_t y; /* Initialize swirl image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); swirl_image=CloneImage(canvas_image,0,0,MagickTrue,exception); if (swirl_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); swirl_image=DestroyImage(swirl_image); return((Image *) NULL); } if (swirl_image->background_color.alpha_trait != UndefinedPixelTrait) (void) SetImageAlphaChannel(swirl_image,OnAlphaChannel,exception); /* Compute scaling factor. */ center.x=(double) canvas_image->columns/2.0; center.y=(double) canvas_image->rows/2.0; radius=MagickMax(center.x,center.y); scale.x=1.0; scale.y=1.0; if (canvas_image->columns > canvas_image->rows) scale.y=(double) canvas_image->columns/(double) canvas_image->rows; else if (canvas_image->columns < canvas_image->rows) scale.x=(double) canvas_image->rows/(double) canvas_image->columns; degrees=(double) DegreesToRadians(degrees); /* Swirl image. */ status=MagickTrue; progress=0; canvas_view=AcquireVirtualCacheView(canvas_image,exception); interpolate_view=AcquireVirtualCacheView(image,exception); swirl_view=AcquireAuthenticCacheView(swirl_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,swirl_image,canvas_image->rows,1) #endif for (y=0; y < (ssize_t) canvas_image->rows; y++) { double distance; PointInfo delta; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) canvas_image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++) { PixelChannel channel = GetPixelChannelChannel(canvas_image,i); PixelTrait traits = GetPixelChannelTraits(canvas_image,channel); PixelTrait swirl_traits = GetPixelChannelTraits(swirl_image, channel); if ((traits == UndefinedPixelTrait) || (swirl_traits == UndefinedPixelTrait)) continue; SetPixelChannel(swirl_image,channel,p[i],q); } } else { double cosine, factor, sine; /* Swirl the pixel. */ factor=1.0-sqrt((double) distance)/radius; sine=sin((double) (degrees*factor*factor)); cosine=cos((double) (degrees*factor*factor)); status=InterpolatePixelChannels(canvas_image,interpolate_view, swirl_image,method,((cosine*delta.x-sine*delta.y)/scale.x+center.x), (double) ((sine*delta.x+cosine*delta.y)/scale.y+center.y),q, exception); if (status == MagickFalse) break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(swirl_image); } if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse) status=MagickFalse; if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,SwirlImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } swirl_view=DestroyCacheView(swirl_view); interpolate_view=DestroyCacheView(interpolate_view); canvas_view=DestroyCacheView(canvas_view); canvas_image=DestroyImage(canvas_image); if (status == MagickFalse) swirl_image=DestroyImage(swirl_image); return(swirl_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TintImage() applies a color vector to each pixel in the image. The length % of the vector is 0 for black and white and at its maximum for the midtones. % The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))) % % The format of the TintImage method is: % % Image *TintImage(const Image *image,const char *blend, % const PixelInfo *tint,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A color value used for tinting. % % o tint: A color value used for tinting. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TintImage(const Image *image,const char *blend, const PixelInfo *tint,ExceptionInfo *exception) { #define TintImageTag "Tint/Image" CacheView *image_view, *tint_view; double intensity; GeometryInfo geometry_info; Image *tint_image; MagickBooleanType status; MagickOffsetType progress; PixelInfo color_vector; MagickStatusType flags; ssize_t y; /* Allocate tint image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); tint_image=CloneImage(image,0,0,MagickTrue,exception); if (tint_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse) { tint_image=DestroyImage(tint_image); return((Image *) NULL); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsPixelInfoGray(tint) == MagickFalse)) (void) SetImageColorspace(tint_image,sRGBColorspace,exception); if (blend == (const char *) NULL) return(tint_image); /* Determine RGB values of the color. */ GetPixelInfo(image,&color_vector); flags=ParseGeometry(blend,&geometry_info); color_vector.red=geometry_info.rho; color_vector.green=geometry_info.rho; color_vector.blue=geometry_info.rho; color_vector.alpha=(MagickRealType) OpaqueAlpha; if ((flags & SigmaValue) != 0) color_vector.green=geometry_info.sigma; if ((flags & XiValue) != 0) color_vector.blue=geometry_info.xi; if ((flags & PsiValue) != 0) color_vector.alpha=geometry_info.psi; if (image->colorspace == CMYKColorspace) { color_vector.black=geometry_info.rho; if ((flags & PsiValue) != 0) color_vector.black=geometry_info.psi; if ((flags & ChiValue) != 0) color_vector.alpha=geometry_info.chi; } intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint); color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity); color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity); color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity); color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity); color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity); /* Tint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); tint_view=AcquireAuthenticCacheView(tint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,tint_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel; double weight; GetPixelInfo(image,&pixel); weight=QuantumScale*GetPixelRed(image,p)-0.5; pixel.red=(MagickRealType) GetPixelRed(image,p)+color_vector.red* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelGreen(image,p)-0.5; pixel.green=(MagickRealType) GetPixelGreen(image,p)+color_vector.green* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelBlue(image,p)-0.5; pixel.blue=(MagickRealType) GetPixelBlue(image,p)+color_vector.blue* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelBlack(image,p)-0.5; pixel.black=(MagickRealType) GetPixelBlack(image,p)+color_vector.black* (1.0-(4.0*(weight*weight))); pixel.alpha=(MagickRealType) GetPixelAlpha(image,p); SetPixelViaPixelInfo(tint_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(tint_image); } if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,TintImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } tint_view=DestroyCacheView(tint_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) tint_image=DestroyImage(tint_image); return(tint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V i g n e t t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % VignetteImage() softens the edges of the image in vignette style. % % The format of the VignetteImage method is: % % Image *VignetteImage(const Image *image,const double radius, % const double sigma,const ssize_t x,const ssize_t y, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x, y: Define the x and y ellipse offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *VignetteImage(const Image *image,const double radius, const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) { char ellipse[MagickPathExtent]; DrawInfo *draw_info; Image *canvas, *blur_image, *oval_image, *vignette_image; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas=CloneImage(image,0,0,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(canvas,DirectClass,exception) == MagickFalse) { canvas=DestroyImage(canvas); return((Image *) NULL); } canvas->alpha_trait=BlendPixelTrait; oval_image=CloneImage(canvas,canvas->columns,canvas->rows,MagickTrue, exception); if (oval_image == (Image *) NULL) { canvas=DestroyImage(canvas); return((Image *) NULL); } (void) QueryColorCompliance("#000000",AllCompliance, &oval_image->background_color,exception); (void) SetImageBackgroundColor(oval_image,exception); draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke, exception); (void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g," "0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x, image->rows/2.0-y); draw_info->primitive=AcquireString(ellipse); (void) DrawImage(oval_image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); blur_image=BlurImage(oval_image,radius,sigma,exception); oval_image=DestroyImage(oval_image); if (blur_image == (Image *) NULL) { canvas=DestroyImage(canvas); return((Image *) NULL); } blur_image->alpha_trait=UndefinedPixelTrait; (void) CompositeImage(canvas,blur_image,IntensityCompositeOp,MagickTrue, 0,0,exception); blur_image=DestroyImage(blur_image); vignette_image=MergeImageLayers(canvas,FlattenLayer,exception); canvas=DestroyImage(canvas); if (vignette_image != (Image *) NULL) (void) TransformImageColorspace(vignette_image,image->colorspace,exception); return(vignette_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveImage() creates a "ripple" effect in the image by shifting the pixels % vertically along a sine wave whose amplitude and wavelength is specified % by the given parameters. % % The format of the WaveImage method is: % % Image *WaveImage(const Image *image,const double amplitude, % const double wave_length,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o amplitude, wave_length: Define the amplitude and wave length of the % sine wave. % % o interpolate: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *canvas_image_view, *wave_view; float *sine_map; Image *canvas_image, *wave_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Initialize wave image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception); wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t) (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); return((Image *) NULL); } /* Allocate sine map. */ sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (float *) NULL) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/wave_length)); /* Wave image. */ status=MagickTrue; progress=0; canvas_image_view=AcquireVirtualCacheView(canvas_image,exception); wave_view=AcquireAuthenticCacheView(wave_image,exception); (void) SetCacheViewVirtualPixelMethod(canvas_image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,wave_image,wave_image->rows,1) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) wave_image->columns; x++) { status=InterpolatePixelChannels(canvas_image,canvas_image_view, wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception); if (status == MagickFalse) break; p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(wave_image); } if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,WaveImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); canvas_image_view=DestroyCacheView(canvas_image_view); canvas_image=DestroyImage(canvas_image); sine_map=(float *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e l e t D e n o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveletDenoiseImage() removes noise from the image using a wavelet % transform. The wavelet transform is a fast hierarchical scheme for % processing an image using a set of consecutive lowpass and high_pass filters, % followed by a decimation. This results in a decomposition into different % scales which can be regarded as different “frequency bands”, determined by % the mother wavelet. Adapted from dcraw.c by David Coffin. % % The format of the WaveletDenoiseImage method is: % % Image *WaveletDenoiseImage(const Image *image,const double threshold, % const double softness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: set the threshold for smoothing. % % o softness: attenuate the smoothing threshold. % % o exception: return any errors or warnings in this structure. % */ static inline void HatTransform(const float *magick_restrict pixels, const size_t stride,const size_t extent,const size_t scale,float *kernel) { const float *magick_restrict p, *magick_restrict q, *magick_restrict r; register ssize_t i; p=pixels; q=pixels+scale*stride; r=pixels+scale*stride; for (i=0; i < (ssize_t) scale; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q-=stride; r+=stride; } for ( ; i < (ssize_t) (extent-scale); i++) { kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride)); p+=stride; } q=p-scale*stride; r=pixels+stride*(extent-2); for ( ; i < (ssize_t) extent; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q+=stride; r-=stride; } } MagickExport Image *WaveletDenoiseImage(const Image *image, const double threshold,const double softness,ExceptionInfo *exception) { CacheView *image_view, *noise_view; float *kernel, *pixels; Image *noise_image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixels_info; ssize_t channel; static const float noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f, 0.0080f, 0.0044f }; /* Initialize noise image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); pixels_info=AcquireVirtualMemory(3*image->columns,image->rows* sizeof(*pixels)); kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1, GetOpenMPMaximumThreads()*sizeof(*kernel)); if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL)) { if (kernel != (float *) NULL) kernel=(float *) RelinquishMagickMemory(kernel); if (pixels_info != (MemoryInfo *) NULL) pixels_info=RelinquishVirtualMemory(pixels_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(float *) GetVirtualMemoryBlob(pixels_info); status=MagickTrue; number_pixels=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++) { register ssize_t i; size_t high_pass, low_pass; ssize_t level, y; PixelChannel pixel_channel; PixelTrait traits; if (status == MagickFalse) continue; traits=GetPixelChannelTraits(image,(PixelChannel) channel); if (traits == UndefinedPixelTrait) continue; pixel_channel=GetPixelChannelChannel(image,channel); if ((pixel_channel != RedPixelChannel) && (pixel_channel != GreenPixelChannel) && (pixel_channel != BluePixelChannel)) continue; /* Copy channel from image to wavelet pixel array. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { pixels[i++]=(float) p[channel]; p+=GetPixelChannels(image); } } /* Low pass filter outputs are called approximation kernel & high pass filters are referred to as detail kernel. The detail kernel have high values in the noisy parts of the signal. */ high_pass=0; for (level=0; level < 5; level++) { double magnitude; ssize_t x, y; low_pass=(size_t) (number_pixels*((level & 0x01)+1)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register float *magick_restrict p, *magick_restrict q; register ssize_t x; p=kernel+id*image->columns; q=pixels+y*image->columns; HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p); q+=low_pass; for (x=0; x < (ssize_t) image->columns; x++) *q++=(*p++); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); register float *magick_restrict p, *magick_restrict q; register ssize_t y; p=kernel+id*image->rows; q=pixels+x+low_pass; HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p); for (y=0; y < (ssize_t) image->rows; y++) { *q=(*p++); q+=image->columns; } } /* To threshold, each coefficient is compared to a threshold value and attenuated / shrunk by some factor. */ magnitude=threshold*noise_levels[level]; for (i=0; i < (ssize_t) number_pixels; ++i) { pixels[high_pass+i]-=pixels[low_pass+i]; if (pixels[high_pass+i] < -magnitude) pixels[high_pass+i]+=magnitude-softness*magnitude; else if (pixels[high_pass+i] > magnitude) pixels[high_pass+i]-=magnitude-softness*magnitude; else pixels[high_pass+i]*=softness; if (high_pass != 0) pixels[i]+=pixels[high_pass+i]; } high_pass=low_pass; } /* Reconstruct image from the thresholded wavelet kernel. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; ssize_t offset; q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } offset=GetPixelChannelOffset(noise_image,pixel_channel); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType pixel; pixel=(MagickRealType) pixels[i]+pixels[low_pass+i]; q[offset]=ClampToQuantum(pixel); i++; q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType) channel,GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); kernel=(float *) RelinquishMagickMemory(kernel); pixels_info=RelinquishVirtualMemory(pixels_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); }
Modulation.h
#pragma once #include <array> #include <cmath> #include <memory> #include <math.h> #include "Common.h" //#include "BaseObjects.h" using namespace std; //template <typename float, int 8> struct Lfo { private: float dt; public: float freqMin = static_cast<float>(0.001f); float freqMax = static_cast<float>(72.21f); array<float, POLY> phase; float* sine; //float* square; //float* saw; //0-1 float* freq; Lfo(const float sampleRate_, float* sine_, float* freq_) { dt = 1.0f / sampleRate_; sine = sine_; freq = freq_; for (int i = 0; i < POLY; i++) { phase[i] = 0.0f; sine[i] = 0.0f; freq[i] = 0.0f; } } //0-1 void process() { for (int i = 0; i < POLY; i++) { phase[i] += freqMin * powf(freqMax / freqMin, freq[i]) * dt; if (phase[i] >= 1.0) { phase[i] -= 1.0; } //square[i] = phase[i] < 0.5 ? 1.0 : 0.0; } //#pragma omp simd get 1200 even if I move approxSine in here manually for (int i = 0; i < POLY; i++) { sine[i] = (aproxSine(2.0f * PI * phase[i]) + 1.0f) * 0.5f; //saw[i] = 1.0f - phase[i]; } } }; //template <typename float, int POLY> struct Envelope { private: const float maxLength = static_cast<float>(20.0); float sampleRate = static_cast<float>(44100.0); array<bool, POLY> decaying; public: float* state = nullptr; float* attack = nullptr; float* decay = nullptr; float* sustain = nullptr; float* release = nullptr; Envelope(const float sampleRate_, float* state_, float* attack_, float* decay_, float* sustain_, float* release_) { sampleRate = sampleRate_; state = state_; attack = attack_; decay = decay_; sustain = sustain_; release = release_; for (int i = 0; i < POLY; i++) { state[i] = 0.0; decaying[i] = false; attack[i] = 0.5; decay[i] = 0.5; sustain[i] = 0.5; release[i] = 0.5; } } void process(array<float, POLY> &in) { for (int i = 0; i < POLY; i++) { if (in[i] >= 1.0f) { if (decaying[i]) { state[i] += powf(20000.0f, 1.0f - decay[i]) / maxLength * (sustain[i] - state[i]) / sampleRate; } else { state[i] += powf(20000.0f, 1.0f - attack[i]) / maxLength * (1.01f - state[i]) / sampleRate; if (state[i] >= 1.0) { state[i] = 1.0; decaying[i] = true; } } } else { // Release state[i] += powf(20000.0f, 1 - release[i]) / maxLength * (0.0f - state[i]) / sampleRate; decaying[i] = false; } } } }; //template <typename float, int 8> struct Noise { private: uint32_t seed = 738; float getLcg() { seed = (seed >> 1) ^ (-(signed int)(seed & 1u) & 0xD0000001u); return static_cast<float>(2.32830643653869629E-10 * seed); } public: float* noise = nullptr; Noise(const uint32_t seed, float* noise) : seed(seed), noise(noise) { for (int i = 0; i < POLY; i++) { noise[i] = getLcg(); } } void process() { for (int i = 0; i < POLY; i++) { noise[i] = getLcg(); } } }; ////template <typename float, int 8> //struct pTrigger { //private: // array<bool, POLY> state; // array<float, POLY> trigger; // const float lowfloathreshold = 0.0f; // const float highfloathreshold = 0.9f; //public: // // pTrigger() { // for (int i = 0; i < POLY; i++) { // state[i] = false; // trigger[i] = 0.0; // } // } // // constexpr array<float, POLY>* get() { // return &trigger; // } // // void process(array<float, POLY>& in) { // for (int i = 0; i < POLY; i++) { // trigger[i] = 0.0; // if (state[i]) { //High // if (in[i] <= lowfloathreshold) { // state[i] = false; // } // } // else { // if (in[i] >= highfloathreshold) { // state[i] = true; // trigger[i] = 1.0; // } // } // } // } // //}; //template <typename float, int 8> struct SandH { private: array<Trigger, POLY> trigger; public: float* state; float* sample; SandH(float* state, float* sample) : state(state), sample(sample) { for (int i = 0; i < POLY; i++) { state[i] = 0.0f; sample[i] = 0.0f; } } void process(array<float, POLY>& in) { for (int i = 0; i < POLY; i++) { if(trigger[i].process(in[i])) { state[i] = sample[i]; } } } }; struct Modulation : ModuleBase { private: unique_ptr<Lfo> lfo = nullptr; unique_ptr<Envelope> audioEnvelope = nullptr; //unique_ptr<Envelope> modEnvelope = nullptr; unique_ptr<Noise> noise = nullptr; unique_ptr<SandH> sandh = nullptr; public: Modulation(const float sampleRate_, shared_ptr<ModMatrix> matrix_, const int channel_) { sampleRate = sampleRate_; matrix = matrix_; channel = channel_; interface.providers = { { "Lfo", 0.0f, 1.0f, nullptr, POLY }, { "S & H", 0.0f, 1.0f, nullptr, POLY }, { "Noise", 0.0f, 1.0f, nullptr, POLY }, { "Audio Envelope", 0.0f, 1.0f, nullptr, POLY }, { "Gate", 0.0f, 1.0f, nullptr, POLY }, { "Const", 0.0f, 1.0f, nullptr, POLY } }; interface.consumers = { { "Lfo Freq", 0.0f, 1.0f, nullptr, POLY }, { "A Env Atk", 0.0f, 1.0f, nullptr, POLY }, { "A Env Dec", 0.0f, 1.0f, nullptr, POLY }, { "A Env Sus", 0.0f, 1.0f, nullptr, POLY }, { "A Env Rel", 0.0f, 1.0f, nullptr, POLY }, { "SandH Input", 0.0f, 1.0f, nullptr, POLY } }; registerInterface(); lfo = make_unique<Lfo>(sampleRate, interface.providers[0].resP, interface.consumers[0].resP); audioEnvelope = make_unique<Envelope>(sampleRate, interface.providers[3].resP, interface.consumers[1].resP, interface.consumers[2].resP, interface.consumers[3].resP, interface.consumers[4].resP); noise = make_unique<Noise>(767, interface.providers[2].resP); sandh = make_unique<SandH>(interface.providers[1].resP, interface.consumers[5].resP); for (int i = 0; i < POLY; i++) { interface.providers[5].resP[i] = 1.0f; } } //Expects gates in void process(array<float, POLY>& in) { lfo->process(); noise->process(); audioEnvelope->process(in); sandh->process(in); for (int i = 0; i < POLY; i++) { interface.providers[4].resP[i] = in[i]; } } //required because modulation isn't unloaded by channel when loading unlike the audio engine //void loadConfig(const json cfg) { // ModuleBase::loadConfig(cfg, true); //} };
2852.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 simd num_threads(28) private(j) 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; }
omp_loop.h
// -*- C++ -*- // Copyright (C) 2007-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/omp_loop.h * @brief Parallelization of embarrassingly parallel execution by * means of an OpenMP for loop. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_OMP_LOOP_H #define _GLIBCXX_PARALLEL_OMP_LOOP_H 1 #include <omp.h> #include <parallel/settings.h> #include <parallel/basic_iterator.h> #include <parallel/base.h> namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using an OpenMP for loop. * * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __o User-supplied functor (comparator, predicate, adding * functor, etc.). * @param __f Functor to @a process an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to @a add a single __result to the already * processed elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template<typename _RAIter, typename _Op, typename _Fu, typename _Red, typename _Result> _Op __for_each_template_random_access_omp_loop(_RAIter __begin, _RAIter __end, _Op __o, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { typedef typename std::iterator_traits<_RAIter>::difference_type _DifferenceType; _DifferenceType __length = __end - __begin; _ThreadIndex __num_threads = __gnu_parallel::min<_DifferenceType> (__get_max_threads(), __length); _Result *__thread_results; # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __thread_results = new _Result[__num_threads]; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __thread_results[__i] = _Result(); } _ThreadIndex __iam = omp_get_thread_num(); #pragma omp for schedule(dynamic, _Settings::get().workstealing_chunk_size) for (_DifferenceType __pos = 0; __pos < __length; ++__pos) __thread_results[__iam] = __r(__thread_results[__iam], __f(__o, __begin+__pos)); } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __output = __r(__output, __thread_results[__i]); delete [] __thread_results; // Points to last element processed (needed as return value for // some algorithms like transform). __f._M_finish_iterator = __begin + __length; return __o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_OMP_LOOP_H */
GB_unop__isinf_bool_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__isinf_bool_fp32 // op(A') function: GB_unop_tran__isinf_bool_fp32 // C type: bool // A type: float // cast: float cij = (aij) // unaryop: cij = isinf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = isinf (x) ; // casting #define GB_CAST(z, aij) \ float z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (aij) ; \ Cx [pC] = isinf (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISINF || GxB_NO_BOOL || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__isinf_bool_fp32 ( bool *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = (aij) ; Cx [p] = isinf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = (aij) ; Cx [p] = isinf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__isinf_bool_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
choleskies_cython.c
/* Generated by Cython 0.29.2 */ #define PY_SSIZE_T_CLEAN #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 < 0x03030000) #error Cython requires Python 2.6+ or Python 3.3+. #else #define CYTHON_ABI "0_29_2" #define CYTHON_HEX_VERSION 0x001D02F0 #define CYTHON_FUTURE_DIVISION 0 #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 #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x02070000 #define HAVE_LONG_LONG #endif #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_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #if PY_VERSION_HEX < 0x03050000 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) #endif #ifndef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) #endif #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #ifdef SIZEOF_VOID_P enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; #endif #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #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 #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 #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int32 uint32_t; #endif #endif #else #include <stdint.h> #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) && __cplusplus >= 201103L #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__ ) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif 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 #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 #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_STACKLESS #define METH_STACKLESS 0 #endif #if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if CYTHON_USE_DICT_VERSIONS #define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ (version_var) = __PYX_GET_DICT_VERSION(dict);\ (cache_var) = (value); #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ (VAR) = __pyx_dict_cached_value;\ } else {\ (VAR) = __pyx_dict_cached_value = (LOOKUP);\ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ }\ } #else #define __PYX_GET_DICT_VERSION(dict) (0) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 #define PyMem_RawMalloc(n) PyMem_Malloc(n) #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) #define PyMem_RawFree(p) PyMem_Free(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x03060000 #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #elif PY_VERSION_HEX >= 0x03000000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #else #define __Pyx_PyThreadState_Current _PyThreadState_Current #endif #if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) #include "pythread.h" #define Py_tss_NEEDS_INIT 0 typedef int Py_tss_t; static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { *key = PyThread_create_key(); return 0; // PyThread_create_key reports success always } static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); *key = Py_tss_NEEDS_INIT; return key; } static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { PyObject_Free(key); } static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { return *key != Py_tss_NEEDS_INIT; } static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { PyThread_delete_key(*key); *key = Py_tss_NEEDS_INIT; } static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { return PyThread_set_key_value(*key, value); } static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { return PyThread_get_key_value(*key); } #endif // TSS (Thread Specific Storage) API #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION #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 #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS #define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) #else #define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) #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_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #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) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #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_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #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])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #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) #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)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? 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 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #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 #define PyObject_Unicode PyObject_Str #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 #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) #else #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #endif #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) : (Py_INCREF(func), func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef __Pyx_PyAsyncMethodsStruct typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__GPy__util__choleskies_cython #define __PYX_HAVE_API__GPy__util__choleskies_cython /* Early includes */ #include <string.h> #include <stdio.h> #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "pythread.h" #include <stdlib.h> #include "pystate.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const 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_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #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 int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { return (size_t) i < (size_t) limit; } #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const 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_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const 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) 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); } #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_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #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 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(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) + 1); 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 CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* Header.proto */ #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[] = { "GPy/util/choleskies_cython.pyx", "__init__.pxd", "stringsource", "type.pxd", }; /* NoFastGil.proto */ #define __Pyx_PyGILState_Ensure PyGILState_Ensure #define __Pyx_PyGILState_Release PyGILState_Release #define __Pyx_FastGIL_Remember() #define __Pyx_FastGIL_Forget() #define __Pyx_FastGilFuncInit() /* MemviewSliceStruct.proto */ 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; #define __Pyx_MemoryView_Len(m) (m.shape[0]) /* Atomics.proto */ #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 && defined(_MSC_VER) && 0 #include <Windows.h> #undef __pyx_atomic_int_type #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 #pragma message ("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 /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* BufferFormatStructs.proto */ #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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":776 * # 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":779 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * #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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":784 * * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":785 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * #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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":800 * # 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * # 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":804 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":805 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":806 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":808 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":809 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":811 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":812 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 * 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; /* "scipy/linalg/cython_blas.pxd":15 * # The original libraries should be linked directly. * * ctypedef float s # <<<<<<<<<<<<<< * ctypedef double d * ctypedef float complex c */ typedef float __pyx_t_5scipy_6linalg_11cython_blas_s; /* "scipy/linalg/cython_blas.pxd":16 * * ctypedef float s * ctypedef double d # <<<<<<<<<<<<<< * ctypedef float complex c * ctypedef double complex z */ typedef double __pyx_t_5scipy_6linalg_11cython_blas_d; /* Declarations.proto */ #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 static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* Declarations.proto */ #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 static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /*--- Type declarations ---*/ struct __pyx_array_obj; struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":817 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":819 * 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":105 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_array_obj { PyObject_HEAD struct __pyx_vtabstruct_array *__pyx_vtab; 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":279 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< * cdef object name * def __init__(self, name): */ struct __pyx_MemviewEnum_obj { PyObject_HEAD PyObject *name; }; /* "View.MemoryView":330 * * @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":961 * * @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":105 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_vtabstruct_array { PyObject *(*get_memview)(struct __pyx_array_obj *); }; static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; /* "View.MemoryView":330 * * @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":961 * * @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) --- */ /* Refnanny.proto */ #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) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* RaiseArgTupleInvalid.proto */ 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); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* GetModuleGlobalName.proto */ #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } #define __Pyx_GetModuleGlobalNameUncached(var, name) {\ PY_UINT64_T __pyx_dict_version;\ PyObject *__pyx_dict_cached_value;\ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); #else #define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); #endif /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #define __Pyx_BUILD_ASSERT_EXPR(cond)\ (sizeof(char [1 - 2*!(cond)]) - 1) #ifndef Py_MEMBER_SIZE #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) #endif static size_t __pyx_pyframe_localsplus_offset = 0; #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets()\ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) #define __Pyx_PyFrame_GetLocalsplus(frame)\ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) #endif /* PyObjectCall.proto */ #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 /* PyObjectCall2Args.proto */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* MemviewSliceInit.proto */ #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); /* None.proto */ static CYTHON_INLINE long __Pyx_div_long(long, long); /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* WriteUnraisableException.proto */ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback, int nogil); /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); #define __Pyx_PyObject_Dict_GetItem(obj, name)\ (likely(PyDict_CheckExact(obj)) ?\ __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* GetTopmostException.proto */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); #endif /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* ArgTypeTest.proto */ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /* IncludeStringH.proto */ #include <string.h> /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* StrEquals.proto */ #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif /* None.proto */ static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* UnaryNegOverflows.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 *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ /* GetAttr.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /* GetItemInt.proto */ #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 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); /* ObjectGetItem.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); #else #define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) #endif /* decode_c_string_utf16.proto */ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 0; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = -1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } /* decode_c_string.proto */ 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)); /* GetAttr3.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /* SwapException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) #define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ /* ListCompAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS 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 /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif /* ListExtend.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 } /* ListAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS 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 /* None.proto */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* HasAttr.proto */ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); /* PyObject_GenericGetAttrNoDict.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr #endif /* PyObject_GenericGetAttr.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr #endif /* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /* SetupReduce.proto */ static int __Pyx_setup_reduce(PyObject* type_obj); /* TypeImport.proto */ #ifndef __PYX_HAVE_RT_ImportType_proto #define __PYX_HAVE_RT_ImportType_proto enum __Pyx_ImportType_CheckSize { __Pyx_ImportType_CheckSize_Error = 0, __Pyx_ImportType_CheckSize_Warn = 1, __Pyx_ImportType_CheckSize_Ignore = 2 }; static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); #endif /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #else static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #endif /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __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); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); #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 /* BufferStructDeclare.proto */ 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; /* MemviewSliceIsContig.proto */ static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); /* OverlappingSlices.proto */ static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize); /* Capsule.proto */ static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); /* IsLittleEndian.proto */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); /* BufferFormatCheck.proto */ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); /* TypeInfoCompare.proto */ static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); /* MemviewSliceValidateAndInit.proto */ 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); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsdsds_double(PyObject *, int writable_flag); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* MemviewDtypeToObject.proto */ static CYTHON_INLINE PyObject *__pyx_memview_get_double(const char *itemp); static CYTHON_INLINE int __pyx_memview_set_double(const char *itemp, PyObject *obj); /* RealImag.proto */ #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(__cplusplus) && CYTHON_CCOMPLEX\ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #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 /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_float(a, b) ((a)==(b)) #define __Pyx_c_sum_float(a, b) ((a)+(b)) #define __Pyx_c_diff_float(a, b) ((a)-(b)) #define __Pyx_c_prod_float(a, b) ((a)*(b)) #define __Pyx_c_quot_float(a, b) ((a)/(b)) #define __Pyx_c_neg_float(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_float(z) ((z)==(float)0) #define __Pyx_c_conj_float(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_float(z) (::std::abs(z)) #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_float(z) ((z)==0) #define __Pyx_c_conj_float(z) (conjf(z)) #if 1 #define __Pyx_c_abs_float(z) (cabsf(z)) #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_double(a, b) ((a)==(b)) #define __Pyx_c_sum_double(a, b) ((a)+(b)) #define __Pyx_c_diff_double(a, b) ((a)-(b)) #define __Pyx_c_prod_double(a, b) ((a)*(b)) #define __Pyx_c_quot_double(a, b) ((a)/(b)) #define __Pyx_c_neg_double(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_double(z) ((z)==(double)0) #define __Pyx_c_conj_double(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_double(z) (::std::abs(z)) #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_double(z) ((z)==0) #define __Pyx_c_conj_double(z) (conj(z)) #if 1 #define __Pyx_c_abs_double(z) (cabs(z)) #define __Pyx_c_pow_double(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); /* MemviewSliceCopyTemplate.proto */ 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); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_double(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *, int writable_flag); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* FunctionImport.proto */ static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ 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 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'cpython.mem' */ /* 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*/ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void); /*proto*/ /* Module declarations from 'scipy.linalg.cython_blas' */ static __pyx_t_5scipy_6linalg_11cython_blas_d (*__pyx_f_5scipy_6linalg_11cython_blas_ddot)(int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *); /*proto*/ static void (*__pyx_f_5scipy_6linalg_11cython_blas_dscal)(int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *); /*proto*/ static void (*__pyx_f_5scipy_6linalg_11cython_blas_dsymv)(char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *); /*proto*/ /* Module declarations from 'GPy.util.choleskies_cython' */ 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 int __pyx_memoryview_thread_locks_used; static PyThread_type_lock __pyx_memoryview_thread_locks[8]; static void __pyx_f_3GPy_4util_17choleskies_cython_chol_backprop(int, __Pyx_memviewslice, __Pyx_memviewslice); /*proto*/ 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 PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "GPy.util.choleskies_cython" extern int __pyx_module_is_main_GPy__util__choleskies_cython; int __pyx_module_is_main_GPy__util__choleskies_cython = 0; /* Implementation of 'GPy.util.choleskies_cython' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_xrange; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_ImportError; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_Ellipsis; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; static const char __pyx_k_D[] = "D"; static const char __pyx_k_L[] = "L"; static const char __pyx_k_M[] = "M"; static const char __pyx_k_N[] = "N"; static const char __pyx_k_O[] = "O"; static const char __pyx_k_c[] = "c"; static const char __pyx_k_d[] = "d"; static const char __pyx_k_i[] = "i"; static const char __pyx_k_j[] = "j"; static const char __pyx_k_k[] = "k"; static const char __pyx_k_m[] = "m"; static const char __pyx_k_dL[] = "dL"; static const char __pyx_k_id[] = "id"; static const char __pyx_k_mm[] = "mm"; static const char __pyx_k_np[] = "np"; static const char __pyx_k_new[] = "__new__"; static const char __pyx_k_obj[] = "obj"; static const char __pyx_k_ret[] = "ret"; static const char __pyx_k_base[] = "base"; static const char __pyx_k_dict[] = "__dict__"; static const char __pyx_k_flat[] = "flat"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mode[] = "mode"; static const char __pyx_k_name[] = "name"; static const char __pyx_k_ndim[] = "ndim"; static const char __pyx_k_pack[] = "pack"; static const char __pyx_k_size[] = "size"; static const char __pyx_k_step[] = "step"; static const char __pyx_k_stop[] = "stop"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_tril[] = "tril"; static const char __pyx_k_ASCII[] = "ASCII"; static const char __pyx_k_class[] = "__class__"; static const char __pyx_k_count[] = "count"; static const char __pyx_k_dL_dK[] = "dL_dK"; static const char __pyx_k_empty[] = "empty"; static const char __pyx_k_error[] = "error"; static const char __pyx_k_flags[] = "flags"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_shape[] = "shape"; static const char __pyx_k_start[] = "start"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_L_cont[] = "L_cont"; static const char __pyx_k_encode[] = "encode"; static const char __pyx_k_format[] = "format"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_name_2[] = "__name__"; static const char __pyx_k_pickle[] = "pickle"; static const char __pyx_k_reduce[] = "__reduce__"; static const char __pyx_k_struct[] = "struct"; static const char __pyx_k_unpack[] = "unpack"; static const char __pyx_k_update[] = "update"; static const char __pyx_k_xrange[] = "xrange"; static const char __pyx_k_asarray[] = "asarray"; static const char __pyx_k_fortran[] = "fortran"; static const char __pyx_k_memview[] = "memview"; static const char __pyx_k_Ellipsis[] = "Ellipsis"; static const char __pyx_k_getstate[] = "__getstate__"; static const char __pyx_k_itemsize[] = "itemsize"; static const char __pyx_k_pyx_type[] = "__pyx_type"; static const char __pyx_k_setstate[] = "__setstate__"; static const char __pyx_k_TypeError[] = "TypeError"; static const char __pyx_k_enumerate[] = "enumerate"; static const char __pyx_k_pyx_state[] = "__pyx_state"; static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; static const char __pyx_k_IndexError[] = "IndexError"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_pyx_result[] = "__pyx_result"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_ImportError[] = "ImportError"; static const char __pyx_k_MemoryError[] = "MemoryError"; static const char __pyx_k_PickleError[] = "PickleError"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; static const char __pyx_k_stringsource[] = "stringsource"; static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; static const char __pyx_k_flat_to_triang[] = "flat_to_triang"; static const char __pyx_k_triang_to_flat[] = "triang_to_flat"; static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; static const char __pyx_k_ascontiguousarray[] = "ascontiguousarray"; static const char __pyx_k_backprop_gradient[] = "backprop_gradient"; static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_strided_and_direct[] = "<strided and direct>"; static const char __pyx_k_strided_and_indirect[] = "<strided and indirect>"; static const char __pyx_k_backprop_gradient_par[] = "backprop_gradient_par"; static const char __pyx_k_contiguous_and_direct[] = "<contiguous and direct>"; static const char __pyx_k_MemoryView_of_r_object[] = "<MemoryView of %r object>"; static const char __pyx_k_MemoryView_of_r_at_0x_x[] = "<MemoryView of %r at 0x%x>"; static const char __pyx_k_backprop_gradient_par_c[] = "backprop_gradient_par_c"; static const char __pyx_k_contiguous_and_indirect[] = "<contiguous and indirect>"; static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; static const char __pyx_k_GPy_util_choleskies_cython[] = "GPy.util.choleskies_cython"; static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; static const char __pyx_k_GPy_util_choleskies_cython_pyx[] = "GPy/util/choleskies_cython.pyx"; static const char __pyx_k_strided_and_direct_or_indirect[] = "<strided and direct or indirect>"; static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static const char __pyx_k_Incompatible_checksums_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (name))"; static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_ASCII; 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_assign_to_read_only_memor; static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; static PyObject *__pyx_kp_s_Cannot_index_with_type_s; static PyObject *__pyx_n_s_D; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_n_s_GPy_util_choleskies_cython; static PyObject *__pyx_kp_s_GPy_util_choleskies_cython_pyx; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; 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_L; static PyObject *__pyx_n_s_L_cont; static PyObject *__pyx_n_s_M; 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_n_s_N; 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_PickleError; 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_n_s_View_MemoryView; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_asarray; static PyObject *__pyx_n_s_ascontiguousarray; static PyObject *__pyx_n_s_backprop_gradient; static PyObject *__pyx_n_s_backprop_gradient_par; static PyObject *__pyx_n_s_backprop_gradient_par_c; 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_n_s_cline_in_traceback; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_count; static PyObject *__pyx_n_s_d; static PyObject *__pyx_n_s_dL; static PyObject *__pyx_n_s_dL_dK; static PyObject *__pyx_n_s_dict; static PyObject *__pyx_n_s_dtype_is_object; static PyObject *__pyx_n_s_empty; static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_flat; static PyObject *__pyx_n_s_flat_to_triang; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; static PyObject *__pyx_n_s_getstate; 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_itemsize; static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; static PyObject *__pyx_n_s_j; static PyObject *__pyx_n_s_k; static PyObject *__pyx_n_s_m; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_memview; static PyObject *__pyx_n_s_mm; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_name_2; 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_new; static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_kp_s_numpy_core_multiarray_failed_to; static PyObject *__pyx_kp_s_numpy_core_umath_failed_to_impor; static PyObject *__pyx_n_s_obj; static PyObject *__pyx_n_s_pack; static PyObject *__pyx_n_s_pickle; static PyObject *__pyx_n_s_pyx_PickleError; static PyObject *__pyx_n_s_pyx_checksum; static PyObject *__pyx_n_s_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_result; static PyObject *__pyx_n_s_pyx_state; static PyObject *__pyx_n_s_pyx_type; static PyObject *__pyx_n_s_pyx_unpickle_Enum; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_reduce; static PyObject *__pyx_n_s_reduce_cython; static PyObject *__pyx_n_s_reduce_ex; static PyObject *__pyx_n_s_ret; static PyObject *__pyx_n_s_setstate; static PyObject *__pyx_n_s_setstate_cython; static PyObject *__pyx_n_s_shape; static PyObject *__pyx_n_s_size; 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_kp_s_stringsource; static PyObject *__pyx_n_s_struct; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_triang_to_flat; static PyObject *__pyx_n_s_tril; 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_update; static PyObject *__pyx_n_s_xrange; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_flat_to_triang(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_flat, int __pyx_v_M); /* proto */ static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_2triang_to_flat(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_L); /* proto */ static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_4backprop_gradient(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L); /* proto */ static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_6backprop_gradient_par(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L); /* proto */ static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_8backprop_gradient_par_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L); /* 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 Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* 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 PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* 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 PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* 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_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* 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 PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_184977713; static PyObject *__pyx_int_neg_1; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; 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__22; 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__21; static PyObject *__pyx_tuple__23; static PyObject *__pyx_tuple__24; static PyObject *__pyx_tuple__25; static PyObject *__pyx_tuple__26; static PyObject *__pyx_tuple__28; static PyObject *__pyx_tuple__30; static PyObject *__pyx_tuple__32; static PyObject *__pyx_tuple__34; static PyObject *__pyx_tuple__36; static PyObject *__pyx_tuple__37; static PyObject *__pyx_tuple__38; static PyObject *__pyx_tuple__39; static PyObject *__pyx_tuple__40; static PyObject *__pyx_tuple__41; static PyObject *__pyx_codeobj__27; static PyObject *__pyx_codeobj__29; static PyObject *__pyx_codeobj__31; static PyObject *__pyx_codeobj__33; static PyObject *__pyx_codeobj__35; static PyObject *__pyx_codeobj__42; /* Late includes */ /* "GPy/util/choleskies_cython.pyx":14 * np.import_array() * * def flat_to_triang(double[:, :] flat, int M): # <<<<<<<<<<<<<< * """take a matrix N x D and return a D X M x M array where * */ /* Python wrapper */ static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_1flat_to_triang(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_3GPy_4util_17choleskies_cython_flat_to_triang[] = "take a matrix N x D and return a D X M x M array where\n\n N = M(M+1)/2\n\n the lower triangluar portion of the d'th slice of the result is filled by the d'th column of flat.\n "; static PyMethodDef __pyx_mdef_3GPy_4util_17choleskies_cython_1flat_to_triang = {"flat_to_triang", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_3GPy_4util_17choleskies_cython_1flat_to_triang, METH_VARARGS|METH_KEYWORDS, __pyx_doc_3GPy_4util_17choleskies_cython_flat_to_triang}; static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_1flat_to_triang(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_flat = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_M; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("flat_to_triang (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_flat,&__pyx_n_s_M,0}; PyObject* values[2] = {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 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flat)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_M)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("flat_to_triang", 1, 2, 2, 1); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "flat_to_triang") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_flat = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_flat.memview)) __PYX_ERR(0, 14, __pyx_L3_error) __pyx_v_M = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_M == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("flat_to_triang", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("GPy.util.choleskies_cython.flat_to_triang", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3GPy_4util_17choleskies_cython_flat_to_triang(__pyx_self, __pyx_v_flat, __pyx_v_M); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_flat_to_triang(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_flat, int __pyx_v_M) { int __pyx_v_D; CYTHON_UNUSED int __pyx_v_N; int __pyx_v_count; __Pyx_memviewslice __pyx_v_ret = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_d; int __pyx_v_m; int __pyx_v_mm; 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; __Pyx_memviewslice __pyx_t_7 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; int __pyx_t_12; int __pyx_t_13; long __pyx_t_14; long __pyx_t_15; int __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; Py_ssize_t __pyx_t_19; Py_ssize_t __pyx_t_20; Py_ssize_t __pyx_t_21; __Pyx_RefNannySetupContext("flat_to_triang", 0); /* "GPy/util/choleskies_cython.pyx":21 * the lower triangluar portion of the d'th slice of the result is filled by the d'th column of flat. * """ * cdef int D = flat.shape[1] # <<<<<<<<<<<<<< * cdef int N = flat.shape[0] * cdef int count = 0 */ __pyx_v_D = (__pyx_v_flat.shape[1]); /* "GPy/util/choleskies_cython.pyx":22 * """ * cdef int D = flat.shape[1] * cdef int N = flat.shape[0] # <<<<<<<<<<<<<< * cdef int count = 0 * cdef double[:, :, ::1] ret = np.zeros((D, M, M)) */ __pyx_v_N = (__pyx_v_flat.shape[0]); /* "GPy/util/choleskies_cython.pyx":23 * cdef int D = flat.shape[1] * cdef int N = flat.shape[0] * cdef int count = 0 # <<<<<<<<<<<<<< * cdef double[:, :, ::1] ret = np.zeros((D, M, M)) * cdef int d, m, mm */ __pyx_v_count = 0; /* "GPy/util/choleskies_cython.pyx":24 * cdef int N = flat.shape[0] * cdef int count = 0 * cdef double[:, :, ::1] ret = np.zeros((D, M, M)) # <<<<<<<<<<<<<< * cdef int d, m, mm * with nogil: */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_D); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_M); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_M); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_5); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_5, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_6); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_7 = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_double(__pyx_t_1, PyBUF_WRITABLE); if (unlikely(!__pyx_t_7.memview)) __PYX_ERR(0, 24, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_ret = __pyx_t_7; __pyx_t_7.memview = NULL; __pyx_t_7.data = NULL; /* "GPy/util/choleskies_cython.pyx":26 * cdef double[:, :, ::1] ret = np.zeros((D, M, M)) * cdef int d, m, mm * with nogil: # <<<<<<<<<<<<<< * for d in range(D): * count = 0 */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { /* "GPy/util/choleskies_cython.pyx":27 * cdef int d, m, mm * with nogil: * for d in range(D): # <<<<<<<<<<<<<< * count = 0 * for m in range(M): */ __pyx_t_8 = __pyx_v_D; __pyx_t_9 = __pyx_t_8; for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { __pyx_v_d = __pyx_t_10; /* "GPy/util/choleskies_cython.pyx":28 * with nogil: * for d in range(D): * count = 0 # <<<<<<<<<<<<<< * for m in range(M): * for mm in range(m+1): */ __pyx_v_count = 0; /* "GPy/util/choleskies_cython.pyx":29 * for d in range(D): * count = 0 * for m in range(M): # <<<<<<<<<<<<<< * for mm in range(m+1): * ret[d, m, mm] = flat[count,d] */ __pyx_t_11 = __pyx_v_M; __pyx_t_12 = __pyx_t_11; for (__pyx_t_13 = 0; __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { __pyx_v_m = __pyx_t_13; /* "GPy/util/choleskies_cython.pyx":30 * count = 0 * for m in range(M): * for mm in range(m+1): # <<<<<<<<<<<<<< * ret[d, m, mm] = flat[count,d] * count += 1 */ __pyx_t_14 = (__pyx_v_m + 1); __pyx_t_15 = __pyx_t_14; for (__pyx_t_16 = 0; __pyx_t_16 < __pyx_t_15; __pyx_t_16+=1) { __pyx_v_mm = __pyx_t_16; /* "GPy/util/choleskies_cython.pyx":31 * for m in range(M): * for mm in range(m+1): * ret[d, m, mm] = flat[count,d] # <<<<<<<<<<<<<< * count += 1 * return ret */ __pyx_t_17 = __pyx_v_count; __pyx_t_18 = __pyx_v_d; if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_v_flat.shape[0]; if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_v_flat.shape[1]; __pyx_t_19 = __pyx_v_d; __pyx_t_20 = __pyx_v_m; __pyx_t_21 = __pyx_v_mm; if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_v_ret.shape[0]; if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_v_ret.shape[1]; if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_v_ret.shape[2]; *((double *) ( /* dim=2 */ ((char *) (((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_ret.data + __pyx_t_19 * __pyx_v_ret.strides[0]) ) + __pyx_t_20 * __pyx_v_ret.strides[1]) )) + __pyx_t_21)) )) = (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_flat.data + __pyx_t_17 * __pyx_v_flat.strides[0]) ) + __pyx_t_18 * __pyx_v_flat.strides[1]) ))); /* "GPy/util/choleskies_cython.pyx":32 * for mm in range(m+1): * ret[d, m, mm] = flat[count,d] * count += 1 # <<<<<<<<<<<<<< * return ret * */ __pyx_v_count = (__pyx_v_count + 1); } } } } /* "GPy/util/choleskies_cython.pyx":26 * cdef double[:, :, ::1] ret = np.zeros((D, M, M)) * cdef int d, m, mm * with nogil: # <<<<<<<<<<<<<< * for d in range(D): * count = 0 */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "GPy/util/choleskies_cython.pyx":33 * ret[d, m, mm] = flat[count,d] * count += 1 * return ret # <<<<<<<<<<<<<< * * def triang_to_flat(double[:, :, :] L): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_ret, 3, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "GPy/util/choleskies_cython.pyx":14 * np.import_array() * * def flat_to_triang(double[:, :] flat, int M): # <<<<<<<<<<<<<< * """take a matrix N x D and return a D X M x M array where * */ /* 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_XDECREF(__pyx_t_6); __PYX_XDEC_MEMVIEW(&__pyx_t_7, 1); __Pyx_AddTraceback("GPy.util.choleskies_cython.flat_to_triang", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_ret, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_flat, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "GPy/util/choleskies_cython.pyx":35 * return ret * * def triang_to_flat(double[:, :, :] L): # <<<<<<<<<<<<<< * cdef int D = L.shape[0] * cdef int M = L.shape[1] */ /* Python wrapper */ static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_3triang_to_flat(PyObject *__pyx_self, PyObject *__pyx_arg_L); /*proto*/ static PyMethodDef __pyx_mdef_3GPy_4util_17choleskies_cython_3triang_to_flat = {"triang_to_flat", (PyCFunction)__pyx_pw_3GPy_4util_17choleskies_cython_3triang_to_flat, METH_O, 0}; static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_3triang_to_flat(PyObject *__pyx_self, PyObject *__pyx_arg_L) { __Pyx_memviewslice __pyx_v_L = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("triang_to_flat (wrapper)", 0); assert(__pyx_arg_L); { __pyx_v_L = __Pyx_PyObject_to_MemoryviewSlice_dsdsds_double(__pyx_arg_L, PyBUF_WRITABLE); if (unlikely(!__pyx_v_L.memview)) __PYX_ERR(0, 35, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("GPy.util.choleskies_cython.triang_to_flat", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3GPy_4util_17choleskies_cython_2triang_to_flat(__pyx_self, __pyx_v_L); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_2triang_to_flat(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_L) { int __pyx_v_D; int __pyx_v_M; int __pyx_v_N; int __pyx_v_count; __Pyx_memviewslice __pyx_v_flat = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_d; int __pyx_v_m; int __pyx_v_mm; 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; __Pyx_memviewslice __pyx_t_6 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; int __pyx_t_12; long __pyx_t_13; long __pyx_t_14; int __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; Py_ssize_t __pyx_t_19; Py_ssize_t __pyx_t_20; __Pyx_RefNannySetupContext("triang_to_flat", 0); /* "GPy/util/choleskies_cython.pyx":36 * * def triang_to_flat(double[:, :, :] L): * cdef int D = L.shape[0] # <<<<<<<<<<<<<< * cdef int M = L.shape[1] * cdef int N = M*(M+1)/2 */ __pyx_v_D = (__pyx_v_L.shape[0]); /* "GPy/util/choleskies_cython.pyx":37 * def triang_to_flat(double[:, :, :] L): * cdef int D = L.shape[0] * cdef int M = L.shape[1] # <<<<<<<<<<<<<< * cdef int N = M*(M+1)/2 * cdef int count = 0 */ __pyx_v_M = (__pyx_v_L.shape[1]); /* "GPy/util/choleskies_cython.pyx":38 * cdef int D = L.shape[0] * cdef int M = L.shape[1] * cdef int N = M*(M+1)/2 # <<<<<<<<<<<<<< * cdef int count = 0 * cdef double[:, ::1] flat = np.empty((N, D)) */ __pyx_v_N = __Pyx_div_long((__pyx_v_M * (__pyx_v_M + 1)), 2); /* "GPy/util/choleskies_cython.pyx":39 * cdef int M = L.shape[1] * cdef int N = M*(M+1)/2 * cdef int count = 0 # <<<<<<<<<<<<<< * cdef double[:, ::1] flat = np.empty((N, D)) * cdef int d, m, mm */ __pyx_v_count = 0; /* "GPy/util/choleskies_cython.pyx":40 * cdef int N = M*(M+1)/2 * cdef int count = 0 * cdef double[:, ::1] flat = np.empty((N, D)) # <<<<<<<<<<<<<< * cdef int d, m, mm * with nogil: */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_empty); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_N); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_D); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1, PyBUF_WRITABLE); if (unlikely(!__pyx_t_6.memview)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_flat = __pyx_t_6; __pyx_t_6.memview = NULL; __pyx_t_6.data = NULL; /* "GPy/util/choleskies_cython.pyx":42 * cdef double[:, ::1] flat = np.empty((N, D)) * cdef int d, m, mm * with nogil: # <<<<<<<<<<<<<< * for d in range(D): * count = 0 */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { /* "GPy/util/choleskies_cython.pyx":43 * cdef int d, m, mm * with nogil: * for d in range(D): # <<<<<<<<<<<<<< * count = 0 * for m in range(M): */ __pyx_t_7 = __pyx_v_D; __pyx_t_8 = __pyx_t_7; for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_d = __pyx_t_9; /* "GPy/util/choleskies_cython.pyx":44 * with nogil: * for d in range(D): * count = 0 # <<<<<<<<<<<<<< * for m in range(M): * for mm in range(m+1): */ __pyx_v_count = 0; /* "GPy/util/choleskies_cython.pyx":45 * for d in range(D): * count = 0 * for m in range(M): # <<<<<<<<<<<<<< * for mm in range(m+1): * flat[count,d] = L[d, m, mm] */ __pyx_t_10 = __pyx_v_M; __pyx_t_11 = __pyx_t_10; for (__pyx_t_12 = 0; __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { __pyx_v_m = __pyx_t_12; /* "GPy/util/choleskies_cython.pyx":46 * count = 0 * for m in range(M): * for mm in range(m+1): # <<<<<<<<<<<<<< * flat[count,d] = L[d, m, mm] * count += 1 */ __pyx_t_13 = (__pyx_v_m + 1); __pyx_t_14 = __pyx_t_13; for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { __pyx_v_mm = __pyx_t_15; /* "GPy/util/choleskies_cython.pyx":47 * for m in range(M): * for mm in range(m+1): * flat[count,d] = L[d, m, mm] # <<<<<<<<<<<<<< * count += 1 * return flat */ __pyx_t_16 = __pyx_v_d; __pyx_t_17 = __pyx_v_m; __pyx_t_18 = __pyx_v_mm; if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_v_L.shape[0]; if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_v_L.shape[1]; if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_v_L.shape[2]; __pyx_t_19 = __pyx_v_count; __pyx_t_20 = __pyx_v_d; if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_v_flat.shape[0]; if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_v_flat.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_flat.data + __pyx_t_19 * __pyx_v_flat.strides[0]) )) + __pyx_t_20)) )) = (*((double *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_16 * __pyx_v_L.strides[0]) ) + __pyx_t_17 * __pyx_v_L.strides[1]) ) + __pyx_t_18 * __pyx_v_L.strides[2]) ))); /* "GPy/util/choleskies_cython.pyx":48 * for mm in range(m+1): * flat[count,d] = L[d, m, mm] * count += 1 # <<<<<<<<<<<<<< * return flat * */ __pyx_v_count = (__pyx_v_count + 1); } } } } /* "GPy/util/choleskies_cython.pyx":42 * cdef double[:, ::1] flat = np.empty((N, D)) * cdef int d, m, mm * with nogil: # <<<<<<<<<<<<<< * for d in range(D): * count = 0 */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "GPy/util/choleskies_cython.pyx":49 * flat[count,d] = L[d, m, mm] * count += 1 * return flat # <<<<<<<<<<<<<< * * def backprop_gradient(double[:, :] dL, double[:, :] L): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_flat, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 49, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "GPy/util/choleskies_cython.pyx":35 * return ret * * def triang_to_flat(double[:, :, :] L): # <<<<<<<<<<<<<< * cdef int D = L.shape[0] * cdef int M = L.shape[1] */ /* 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_XDEC_MEMVIEW(&__pyx_t_6, 1); __Pyx_AddTraceback("GPy.util.choleskies_cython.triang_to_flat", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_L, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_flat, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "GPy/util/choleskies_cython.pyx":51 * return flat * * def backprop_gradient(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ /* Python wrapper */ static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_5backprop_gradient(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_3GPy_4util_17choleskies_cython_5backprop_gradient = {"backprop_gradient", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_3GPy_4util_17choleskies_cython_5backprop_gradient, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_5backprop_gradient(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_dL = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_L = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("backprop_gradient (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_dL,&__pyx_n_s_L,0}; PyObject* values[2] = {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 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dL)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_L)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("backprop_gradient", 1, 2, 2, 1); __PYX_ERR(0, 51, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "backprop_gradient") < 0)) __PYX_ERR(0, 51, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_dL = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_dL.memview)) __PYX_ERR(0, 51, __pyx_L3_error) __pyx_v_L = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_L.memview)) __PYX_ERR(0, 51, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("backprop_gradient", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 51, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("GPy.util.choleskies_cython.backprop_gradient", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3GPy_4util_17choleskies_cython_4backprop_gradient(__pyx_self, __pyx_v_dL, __pyx_v_L); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_4backprop_gradient(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L) { __Pyx_memviewslice __pyx_v_dL_dK = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_N; int __pyx_v_k; int __pyx_v_j; int __pyx_v_i; 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; __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; int __pyx_t_12; Py_ssize_t __pyx_t_13; Py_ssize_t __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; Py_ssize_t __pyx_t_19; Py_ssize_t __pyx_t_20; Py_ssize_t __pyx_t_21; Py_ssize_t __pyx_t_22; Py_ssize_t __pyx_t_23; Py_ssize_t __pyx_t_24; Py_ssize_t __pyx_t_25; Py_ssize_t __pyx_t_26; Py_ssize_t __pyx_t_27; Py_ssize_t __pyx_t_28; Py_ssize_t __pyx_t_29; Py_ssize_t __pyx_t_30; Py_ssize_t __pyx_t_31; Py_ssize_t __pyx_t_32; Py_ssize_t __pyx_t_33; Py_ssize_t __pyx_t_34; Py_ssize_t __pyx_t_35; Py_ssize_t __pyx_t_36; Py_ssize_t __pyx_t_37; Py_ssize_t __pyx_t_38; __Pyx_RefNannySetupContext("backprop_gradient", 0); /* "GPy/util/choleskies_cython.pyx":52 * * def backprop_gradient(double[:, :] dL, double[:, :] L): * cdef double[:, ::1] dL_dK = np.tril(dL) # <<<<<<<<<<<<<< * cdef int N = L.shape[0] * cdef int k, j, i */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 52, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_tril); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 52, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_dL, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 52, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 52, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1, PyBUF_WRITABLE); if (unlikely(!__pyx_t_5.memview)) __PYX_ERR(0, 52, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_dL_dK = __pyx_t_5; __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; /* "GPy/util/choleskies_cython.pyx":53 * def backprop_gradient(double[:, :] dL, double[:, :] L): * cdef double[:, ::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] # <<<<<<<<<<<<<< * cdef int k, j, i * with nogil: */ __pyx_v_N = (__pyx_v_L.shape[0]); /* "GPy/util/choleskies_cython.pyx":55 * cdef int N = L.shape[0] * cdef int k, j, i * with nogil: # <<<<<<<<<<<<<< * for k in range(N - 1, -1, -1): * for j in range(k + 1, N): */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { /* "GPy/util/choleskies_cython.pyx":56 * cdef int k, j, i * with nogil: * for k in range(N - 1, -1, -1): # <<<<<<<<<<<<<< * for j in range(k + 1, N): * for i in range(j, N): */ for (__pyx_t_6 = (__pyx_v_N - 1); __pyx_t_6 > -1; __pyx_t_6-=1) { __pyx_v_k = __pyx_t_6; /* "GPy/util/choleskies_cython.pyx":57 * with nogil: * for k in range(N - 1, -1, -1): * for j in range(k + 1, N): # <<<<<<<<<<<<<< * for i in range(j, N): * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] */ __pyx_t_7 = __pyx_v_N; __pyx_t_8 = __pyx_t_7; for (__pyx_t_9 = (__pyx_v_k + 1); __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_j = __pyx_t_9; /* "GPy/util/choleskies_cython.pyx":58 * for k in range(N - 1, -1, -1): * for j in range(k + 1, N): * for i in range(j, N): # <<<<<<<<<<<<<< * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] * dL_dK[j, k] -= dL_dK[i, j] * L[i, k] */ __pyx_t_10 = __pyx_v_N; __pyx_t_11 = __pyx_t_10; for (__pyx_t_12 = __pyx_v_j; __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { __pyx_v_i = __pyx_t_12; /* "GPy/util/choleskies_cython.pyx":59 * for j in range(k + 1, N): * for i in range(j, N): * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] # <<<<<<<<<<<<<< * dL_dK[j, k] -= dL_dK[i, j] * L[i, k] * for j in range(k + 1, N): */ __pyx_t_13 = __pyx_v_i; __pyx_t_14 = __pyx_v_j; if (__pyx_t_13 < 0) __pyx_t_13 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_v_dL_dK.shape[1]; __pyx_t_15 = __pyx_v_j; __pyx_t_16 = __pyx_v_k; if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_v_L.shape[0]; if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_v_L.shape[1]; __pyx_t_17 = __pyx_v_i; __pyx_t_18 = __pyx_v_k; if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_17 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_18)) )) -= ((*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_13 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_14)) ))) * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_15 * __pyx_v_L.strides[0]) ) + __pyx_t_16 * __pyx_v_L.strides[1]) )))); /* "GPy/util/choleskies_cython.pyx":60 * for i in range(j, N): * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] * dL_dK[j, k] -= dL_dK[i, j] * L[i, k] # <<<<<<<<<<<<<< * for j in range(k + 1, N): * dL_dK[j, k] /= L[k, k] */ __pyx_t_19 = __pyx_v_i; __pyx_t_20 = __pyx_v_j; if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_v_dL_dK.shape[1]; __pyx_t_21 = __pyx_v_i; __pyx_t_22 = __pyx_v_k; if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_v_L.shape[0]; if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_v_L.shape[1]; __pyx_t_23 = __pyx_v_j; __pyx_t_24 = __pyx_v_k; if (__pyx_t_23 < 0) __pyx_t_23 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_24 < 0) __pyx_t_24 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_23 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_24)) )) -= ((*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_19 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_20)) ))) * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_21 * __pyx_v_L.strides[0]) ) + __pyx_t_22 * __pyx_v_L.strides[1]) )))); } } /* "GPy/util/choleskies_cython.pyx":61 * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] * dL_dK[j, k] -= dL_dK[i, j] * L[i, k] * for j in range(k + 1, N): # <<<<<<<<<<<<<< * dL_dK[j, k] /= L[k, k] * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] */ __pyx_t_7 = __pyx_v_N; __pyx_t_8 = __pyx_t_7; for (__pyx_t_9 = (__pyx_v_k + 1); __pyx_t_9 < __pyx_t_8; __pyx_t_9+=1) { __pyx_v_j = __pyx_t_9; /* "GPy/util/choleskies_cython.pyx":62 * dL_dK[j, k] -= dL_dK[i, j] * L[i, k] * for j in range(k + 1, N): * dL_dK[j, k] /= L[k, k] # <<<<<<<<<<<<<< * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] * dL_dK[k, k] /= (2. * L[k, k]) */ __pyx_t_25 = __pyx_v_k; __pyx_t_26 = __pyx_v_k; if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_v_L.shape[0]; if (__pyx_t_26 < 0) __pyx_t_26 += __pyx_v_L.shape[1]; __pyx_t_27 = __pyx_v_j; __pyx_t_28 = __pyx_v_k; if (__pyx_t_27 < 0) __pyx_t_27 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_28 < 0) __pyx_t_28 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_27 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_28)) )) /= (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_25 * __pyx_v_L.strides[0]) ) + __pyx_t_26 * __pyx_v_L.strides[1]) ))); /* "GPy/util/choleskies_cython.pyx":63 * for j in range(k + 1, N): * dL_dK[j, k] /= L[k, k] * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] # <<<<<<<<<<<<<< * dL_dK[k, k] /= (2. * L[k, k]) * return dL_dK */ __pyx_t_29 = __pyx_v_j; __pyx_t_30 = __pyx_v_k; if (__pyx_t_29 < 0) __pyx_t_29 += __pyx_v_L.shape[0]; if (__pyx_t_30 < 0) __pyx_t_30 += __pyx_v_L.shape[1]; __pyx_t_31 = __pyx_v_j; __pyx_t_32 = __pyx_v_k; if (__pyx_t_31 < 0) __pyx_t_31 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_32 < 0) __pyx_t_32 += __pyx_v_dL_dK.shape[1]; __pyx_t_33 = __pyx_v_k; __pyx_t_34 = __pyx_v_k; if (__pyx_t_33 < 0) __pyx_t_33 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_34 < 0) __pyx_t_34 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_33 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_34)) )) -= ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_29 * __pyx_v_L.strides[0]) ) + __pyx_t_30 * __pyx_v_L.strides[1]) ))) * (*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_31 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_32)) )))); } /* "GPy/util/choleskies_cython.pyx":64 * dL_dK[j, k] /= L[k, k] * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] * dL_dK[k, k] /= (2. * L[k, k]) # <<<<<<<<<<<<<< * return dL_dK * */ __pyx_t_35 = __pyx_v_k; __pyx_t_36 = __pyx_v_k; if (__pyx_t_35 < 0) __pyx_t_35 += __pyx_v_L.shape[0]; if (__pyx_t_36 < 0) __pyx_t_36 += __pyx_v_L.shape[1]; __pyx_t_37 = __pyx_v_k; __pyx_t_38 = __pyx_v_k; if (__pyx_t_37 < 0) __pyx_t_37 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_38 < 0) __pyx_t_38 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_37 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_38)) )) /= (2. * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_35 * __pyx_v_L.strides[0]) ) + __pyx_t_36 * __pyx_v_L.strides[1]) )))); } } /* "GPy/util/choleskies_cython.pyx":55 * cdef int N = L.shape[0] * cdef int k, j, i * with nogil: # <<<<<<<<<<<<<< * for k in range(N - 1, -1, -1): * for j in range(k + 1, N): */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "GPy/util/choleskies_cython.pyx":65 * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] * dL_dK[k, k] /= (2. * L[k, k]) * return dL_dK # <<<<<<<<<<<<<< * * def backprop_gradient_par(double[:,:] dL, double[:,:] L): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_dL_dK, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "GPy/util/choleskies_cython.pyx":51 * return flat * * def backprop_gradient(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ /* 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_XDEC_MEMVIEW(&__pyx_t_5, 1); __Pyx_AddTraceback("GPy.util.choleskies_cython.backprop_gradient", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_dL_dK, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_dL, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_L, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "GPy/util/choleskies_cython.pyx":67 * return dL_dK * * def backprop_gradient_par(double[:,:] dL, double[:,:] L): # <<<<<<<<<<<<<< * cdef double[:,::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ /* Python wrapper */ static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_7backprop_gradient_par(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_3GPy_4util_17choleskies_cython_7backprop_gradient_par = {"backprop_gradient_par", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_3GPy_4util_17choleskies_cython_7backprop_gradient_par, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_7backprop_gradient_par(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_dL = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_L = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("backprop_gradient_par (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_dL,&__pyx_n_s_L,0}; PyObject* values[2] = {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 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dL)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_L)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("backprop_gradient_par", 1, 2, 2, 1); __PYX_ERR(0, 67, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "backprop_gradient_par") < 0)) __PYX_ERR(0, 67, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_dL = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_dL.memview)) __PYX_ERR(0, 67, __pyx_L3_error) __pyx_v_L = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_L.memview)) __PYX_ERR(0, 67, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("backprop_gradient_par", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 67, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("GPy.util.choleskies_cython.backprop_gradient_par", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3GPy_4util_17choleskies_cython_6backprop_gradient_par(__pyx_self, __pyx_v_dL, __pyx_v_L); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_6backprop_gradient_par(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L) { __Pyx_memviewslice __pyx_v_dL_dK = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_N; int __pyx_v_k; int __pyx_v_j; int __pyx_v_i; 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; __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_t_6; long __pyx_t_7; int __pyx_t_8; long __pyx_t_9; long __pyx_t_10; long __pyx_t_11; long __pyx_t_12; int __pyx_t_13; Py_ssize_t __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; Py_ssize_t __pyx_t_19; int __pyx_t_20; int __pyx_t_21; Py_ssize_t __pyx_t_22; Py_ssize_t __pyx_t_23; Py_ssize_t __pyx_t_24; Py_ssize_t __pyx_t_25; Py_ssize_t __pyx_t_26; Py_ssize_t __pyx_t_27; Py_ssize_t __pyx_t_28; Py_ssize_t __pyx_t_29; Py_ssize_t __pyx_t_30; Py_ssize_t __pyx_t_31; Py_ssize_t __pyx_t_32; Py_ssize_t __pyx_t_33; Py_ssize_t __pyx_t_34; Py_ssize_t __pyx_t_35; Py_ssize_t __pyx_t_36; Py_ssize_t __pyx_t_37; Py_ssize_t __pyx_t_38; Py_ssize_t __pyx_t_39; Py_ssize_t __pyx_t_40; Py_ssize_t __pyx_t_41; __Pyx_RefNannySetupContext("backprop_gradient_par", 0); /* "GPy/util/choleskies_cython.pyx":68 * * def backprop_gradient_par(double[:,:] dL, double[:,:] L): * cdef double[:,::1] dL_dK = np.tril(dL) # <<<<<<<<<<<<<< * cdef int N = L.shape[0] * cdef int k, j, i */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_tril); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_dL, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1, PyBUF_WRITABLE); if (unlikely(!__pyx_t_5.memview)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_dL_dK = __pyx_t_5; __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; /* "GPy/util/choleskies_cython.pyx":69 * def backprop_gradient_par(double[:,:] dL, double[:,:] L): * cdef double[:,::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] # <<<<<<<<<<<<<< * cdef int k, j, i * with nogil: */ __pyx_v_N = (__pyx_v_L.shape[0]); /* "GPy/util/choleskies_cython.pyx":71 * cdef int N = L.shape[0] * cdef int k, j, i * with nogil: # <<<<<<<<<<<<<< * for k in range(N - 1, -1, -1): * with parallel(): */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { /* "GPy/util/choleskies_cython.pyx":72 * cdef int k, j, i * with nogil: * for k in range(N - 1, -1, -1): # <<<<<<<<<<<<<< * with parallel(): * for i in prange(k + 1, N): */ for (__pyx_t_6 = (__pyx_v_N - 1); __pyx_t_6 > -1; __pyx_t_6-=1) { __pyx_v_k = __pyx_t_6; /* "GPy/util/choleskies_cython.pyx":73 * with nogil: * for k in range(N - 1, -1, -1): * with parallel(): # <<<<<<<<<<<<<< * for i in prange(k + 1, N): * for j in range(k+1, i+1): */ { #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 #ifdef _OPENMP #pragma omp parallel private(__pyx_t_10, __pyx_t_11, __pyx_t_12, __pyx_t_13, __pyx_t_14, __pyx_t_15, __pyx_t_16, __pyx_t_17, __pyx_t_18, __pyx_t_19, __pyx_t_20, __pyx_t_21, __pyx_t_22, __pyx_t_23, __pyx_t_24, __pyx_t_25, __pyx_t_26, __pyx_t_27, __pyx_t_7, __pyx_t_8, __pyx_t_9) #endif /* _OPENMP */ { /* "GPy/util/choleskies_cython.pyx":74 * for k in range(N - 1, -1, -1): * with parallel(): * for i in prange(k + 1, N): # <<<<<<<<<<<<<< * for j in range(k+1, i+1): * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] */ __pyx_t_7 = (__pyx_v_k + 1); __pyx_t_8 = __pyx_v_N; if (1 == 0) abort(); { __pyx_t_10 = (__pyx_t_8 - __pyx_t_7 + 1 - 1/abs(1)) / 1; if (__pyx_t_10 > 0) { #ifdef _OPENMP #pragma omp for firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) lastprivate(__pyx_v_j) #endif /* _OPENMP */ for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_10; __pyx_t_9++){ { __pyx_v_i = (int)(__pyx_t_7 + 1 * __pyx_t_9); /* Initialize private variables to invalid values */ __pyx_v_j = ((int)0xbad0bad0); /* "GPy/util/choleskies_cython.pyx":75 * with parallel(): * for i in prange(k + 1, N): * for j in range(k+1, i+1): # <<<<<<<<<<<<<< * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] * for j in range(i, N): */ __pyx_t_11 = (__pyx_v_i + 1); __pyx_t_12 = __pyx_t_11; for (__pyx_t_13 = (__pyx_v_k + 1); __pyx_t_13 < __pyx_t_12; __pyx_t_13+=1) { __pyx_v_j = __pyx_t_13; /* "GPy/util/choleskies_cython.pyx":76 * for i in prange(k + 1, N): * for j in range(k+1, i+1): * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] # <<<<<<<<<<<<<< * for j in range(i, N): * dL_dK[i, k] -= dL_dK[j, i] * L[j, k] */ __pyx_t_14 = __pyx_v_i; __pyx_t_15 = __pyx_v_j; if (__pyx_t_14 < 0) __pyx_t_14 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_v_dL_dK.shape[1]; __pyx_t_16 = __pyx_v_j; __pyx_t_17 = __pyx_v_k; if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_v_L.shape[0]; if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_v_L.shape[1]; __pyx_t_18 = __pyx_v_i; __pyx_t_19 = __pyx_v_k; if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_18 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_19)) )) -= ((*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_14 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_15)) ))) * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_16 * __pyx_v_L.strides[0]) ) + __pyx_t_17 * __pyx_v_L.strides[1]) )))); } /* "GPy/util/choleskies_cython.pyx":77 * for j in range(k+1, i+1): * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] * for j in range(i, N): # <<<<<<<<<<<<<< * dL_dK[i, k] -= dL_dK[j, i] * L[j, k] * for j in range(k + 1, N): */ __pyx_t_13 = __pyx_v_N; __pyx_t_20 = __pyx_t_13; for (__pyx_t_21 = __pyx_v_i; __pyx_t_21 < __pyx_t_20; __pyx_t_21+=1) { __pyx_v_j = __pyx_t_21; /* "GPy/util/choleskies_cython.pyx":78 * dL_dK[i, k] -= dL_dK[i, j] * L[j, k] * for j in range(i, N): * dL_dK[i, k] -= dL_dK[j, i] * L[j, k] # <<<<<<<<<<<<<< * for j in range(k + 1, N): * dL_dK[j, k] /= L[k, k] */ __pyx_t_22 = __pyx_v_j; __pyx_t_23 = __pyx_v_i; if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_23 < 0) __pyx_t_23 += __pyx_v_dL_dK.shape[1]; __pyx_t_24 = __pyx_v_j; __pyx_t_25 = __pyx_v_k; if (__pyx_t_24 < 0) __pyx_t_24 += __pyx_v_L.shape[0]; if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_v_L.shape[1]; __pyx_t_26 = __pyx_v_i; __pyx_t_27 = __pyx_v_k; if (__pyx_t_26 < 0) __pyx_t_26 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_27 < 0) __pyx_t_27 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_26 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_27)) )) -= ((*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_22 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_23)) ))) * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_24 * __pyx_v_L.strides[0]) ) + __pyx_t_25 * __pyx_v_L.strides[1]) )))); } } } } } } } #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 /* "GPy/util/choleskies_cython.pyx":79 * for j in range(i, N): * dL_dK[i, k] -= dL_dK[j, i] * L[j, k] * for j in range(k + 1, N): # <<<<<<<<<<<<<< * dL_dK[j, k] /= L[k, k] * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] */ __pyx_t_8 = __pyx_v_N; __pyx_t_13 = __pyx_t_8; for (__pyx_t_20 = (__pyx_v_k + 1); __pyx_t_20 < __pyx_t_13; __pyx_t_20+=1) { __pyx_v_j = __pyx_t_20; /* "GPy/util/choleskies_cython.pyx":80 * dL_dK[i, k] -= dL_dK[j, i] * L[j, k] * for j in range(k + 1, N): * dL_dK[j, k] /= L[k, k] # <<<<<<<<<<<<<< * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] * dL_dK[k, k] /= (2. * L[k, k]) */ __pyx_t_28 = __pyx_v_k; __pyx_t_29 = __pyx_v_k; if (__pyx_t_28 < 0) __pyx_t_28 += __pyx_v_L.shape[0]; if (__pyx_t_29 < 0) __pyx_t_29 += __pyx_v_L.shape[1]; __pyx_t_30 = __pyx_v_j; __pyx_t_31 = __pyx_v_k; if (__pyx_t_30 < 0) __pyx_t_30 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_31 < 0) __pyx_t_31 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_30 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_31)) )) /= (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_28 * __pyx_v_L.strides[0]) ) + __pyx_t_29 * __pyx_v_L.strides[1]) ))); /* "GPy/util/choleskies_cython.pyx":81 * for j in range(k + 1, N): * dL_dK[j, k] /= L[k, k] * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] # <<<<<<<<<<<<<< * dL_dK[k, k] /= (2. * L[k, k]) * return dL_dK */ __pyx_t_32 = __pyx_v_j; __pyx_t_33 = __pyx_v_k; if (__pyx_t_32 < 0) __pyx_t_32 += __pyx_v_L.shape[0]; if (__pyx_t_33 < 0) __pyx_t_33 += __pyx_v_L.shape[1]; __pyx_t_34 = __pyx_v_j; __pyx_t_35 = __pyx_v_k; if (__pyx_t_34 < 0) __pyx_t_34 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_35 < 0) __pyx_t_35 += __pyx_v_dL_dK.shape[1]; __pyx_t_36 = __pyx_v_k; __pyx_t_37 = __pyx_v_k; if (__pyx_t_36 < 0) __pyx_t_36 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_37 < 0) __pyx_t_37 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_36 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_37)) )) -= ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_32 * __pyx_v_L.strides[0]) ) + __pyx_t_33 * __pyx_v_L.strides[1]) ))) * (*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_34 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_35)) )))); } /* "GPy/util/choleskies_cython.pyx":82 * dL_dK[j, k] /= L[k, k] * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] * dL_dK[k, k] /= (2. * L[k, k]) # <<<<<<<<<<<<<< * return dL_dK * */ __pyx_t_38 = __pyx_v_k; __pyx_t_39 = __pyx_v_k; if (__pyx_t_38 < 0) __pyx_t_38 += __pyx_v_L.shape[0]; if (__pyx_t_39 < 0) __pyx_t_39 += __pyx_v_L.shape[1]; __pyx_t_40 = __pyx_v_k; __pyx_t_41 = __pyx_v_k; if (__pyx_t_40 < 0) __pyx_t_40 += __pyx_v_dL_dK.shape[0]; if (__pyx_t_41 < 0) __pyx_t_41 += __pyx_v_dL_dK.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL_dK.data + __pyx_t_40 * __pyx_v_dL_dK.strides[0]) )) + __pyx_t_41)) )) /= (2. * (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_L.data + __pyx_t_38 * __pyx_v_L.strides[0]) ) + __pyx_t_39 * __pyx_v_L.strides[1]) )))); } } /* "GPy/util/choleskies_cython.pyx":71 * cdef int N = L.shape[0] * cdef int k, j, i * with nogil: # <<<<<<<<<<<<<< * for k in range(N - 1, -1, -1): * with parallel(): */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "GPy/util/choleskies_cython.pyx":83 * dL_dK[k, k] -= L[j, k] * dL_dK[j, k] * dL_dK[k, k] /= (2. * L[k, k]) * return dL_dK # <<<<<<<<<<<<<< * * cdef void chol_backprop(int N, double[:, ::1] dL, double[:, ::1] L) nogil: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_dL_dK, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "GPy/util/choleskies_cython.pyx":67 * return dL_dK * * def backprop_gradient_par(double[:,:] dL, double[:,:] L): # <<<<<<<<<<<<<< * cdef double[:,::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ /* 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_XDEC_MEMVIEW(&__pyx_t_5, 1); __Pyx_AddTraceback("GPy.util.choleskies_cython.backprop_gradient_par", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_dL_dK, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_dL, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_L, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "GPy/util/choleskies_cython.pyx":85 * return dL_dK * * cdef void chol_backprop(int N, double[:, ::1] dL, double[:, ::1] L) nogil: # <<<<<<<<<<<<<< * cdef int i, k, n * */ static void __pyx_f_3GPy_4util_17choleskies_cython_chol_backprop(int __pyx_v_N, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L) { int __pyx_v_i; int __pyx_v_k; int __pyx_v_n; double __pyx_v_alpha; double __pyx_v_beta; int __pyx_v_incx; double __pyx_v_scale; Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; int __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; Py_ssize_t __pyx_t_10; Py_ssize_t __pyx_t_11; long __pyx_t_12; long __pyx_t_13; int __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; Py_ssize_t __pyx_t_17; Py_ssize_t __pyx_t_18; Py_ssize_t __pyx_t_19; Py_ssize_t __pyx_t_20; Py_ssize_t __pyx_t_21; Py_ssize_t __pyx_t_22; double __pyx_t_23; Py_ssize_t __pyx_t_24; Py_ssize_t __pyx_t_25; Py_ssize_t __pyx_t_26; Py_ssize_t __pyx_t_27; Py_ssize_t __pyx_t_28; Py_ssize_t __pyx_t_29; Py_ssize_t __pyx_t_30; Py_ssize_t __pyx_t_31; Py_ssize_t __pyx_t_32; Py_ssize_t __pyx_t_33; Py_ssize_t __pyx_t_34; Py_ssize_t __pyx_t_35; /* "GPy/util/choleskies_cython.pyx":89 * * # DSYMV required constant arguments * cdef double alpha=-1, beta=1 # <<<<<<<<<<<<<< * cdef int incx=N * */ __pyx_v_alpha = -1.0; __pyx_v_beta = 1.0; /* "GPy/util/choleskies_cython.pyx":90 * # DSYMV required constant arguments * cdef double alpha=-1, beta=1 * cdef int incx=N # <<<<<<<<<<<<<< * * # DSCAL required arguments */ __pyx_v_incx = __pyx_v_N; /* "GPy/util/choleskies_cython.pyx":95 * cdef double scale * * dL[N - 1, N - 1] /= (2. * L[N - 1, N - 1]) # <<<<<<<<<<<<<< * for k in range(N-2, -1, -1): * n = N-k-1 */ __pyx_t_1 = (__pyx_v_N - 1); __pyx_t_2 = (__pyx_v_N - 1); if (__pyx_t_1 < 0) __pyx_t_1 += __pyx_v_L.shape[0]; if (__pyx_t_2 < 0) __pyx_t_2 += __pyx_v_L.shape[1]; __pyx_t_3 = (__pyx_v_N - 1); __pyx_t_4 = (__pyx_v_N - 1); if (__pyx_t_3 < 0) __pyx_t_3 += __pyx_v_dL.shape[0]; if (__pyx_t_4 < 0) __pyx_t_4 += __pyx_v_dL.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_3 * __pyx_v_dL.strides[0]) )) + __pyx_t_4)) )) /= (2. * (*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_L.data + __pyx_t_1 * __pyx_v_L.strides[0]) )) + __pyx_t_2)) )))); /* "GPy/util/choleskies_cython.pyx":96 * * dL[N - 1, N - 1] /= (2. * L[N - 1, N - 1]) * for k in range(N-2, -1, -1): # <<<<<<<<<<<<<< * n = N-k-1 * cblas.dsymv(uplo='u', n=&n, alpha=&alpha, a=&dL[k + 1, k + 1], lda=&N, x=&L[k + 1, k], incx=&incx, */ for (__pyx_t_5 = (__pyx_v_N - 2); __pyx_t_5 > -1; __pyx_t_5-=1) { __pyx_v_k = __pyx_t_5; /* "GPy/util/choleskies_cython.pyx":97 * dL[N - 1, N - 1] /= (2. * L[N - 1, N - 1]) * for k in range(N-2, -1, -1): * n = N-k-1 # <<<<<<<<<<<<<< * cblas.dsymv(uplo='u', n=&n, alpha=&alpha, a=&dL[k + 1, k + 1], lda=&N, x=&L[k + 1, k], incx=&incx, * beta=&beta, y=&dL[k + 1, k], incy=&N) */ __pyx_v_n = ((__pyx_v_N - __pyx_v_k) - 1); /* "GPy/util/choleskies_cython.pyx":98 * for k in range(N-2, -1, -1): * n = N-k-1 * cblas.dsymv(uplo='u', n=&n, alpha=&alpha, a=&dL[k + 1, k + 1], lda=&N, x=&L[k + 1, k], incx=&incx, # <<<<<<<<<<<<<< * beta=&beta, y=&dL[k + 1, k], incy=&N) * */ __pyx_t_6 = (__pyx_v_k + 1); __pyx_t_7 = (__pyx_v_k + 1); if (__pyx_t_6 < 0) __pyx_t_6 += __pyx_v_dL.shape[0]; if (__pyx_t_7 < 0) __pyx_t_7 += __pyx_v_dL.shape[1]; __pyx_t_8 = (__pyx_v_k + 1); __pyx_t_9 = __pyx_v_k; if (__pyx_t_8 < 0) __pyx_t_8 += __pyx_v_L.shape[0]; if (__pyx_t_9 < 0) __pyx_t_9 += __pyx_v_L.shape[1]; /* "GPy/util/choleskies_cython.pyx":99 * n = N-k-1 * cblas.dsymv(uplo='u', n=&n, alpha=&alpha, a=&dL[k + 1, k + 1], lda=&N, x=&L[k + 1, k], incx=&incx, * beta=&beta, y=&dL[k + 1, k], incy=&N) # <<<<<<<<<<<<<< * * for i in xrange(0, N - k - 1): */ __pyx_t_10 = (__pyx_v_k + 1); __pyx_t_11 = __pyx_v_k; if (__pyx_t_10 < 0) __pyx_t_10 += __pyx_v_dL.shape[0]; if (__pyx_t_11 < 0) __pyx_t_11 += __pyx_v_dL.shape[1]; /* "GPy/util/choleskies_cython.pyx":98 * for k in range(N-2, -1, -1): * n = N-k-1 * cblas.dsymv(uplo='u', n=&n, alpha=&alpha, a=&dL[k + 1, k + 1], lda=&N, x=&L[k + 1, k], incx=&incx, # <<<<<<<<<<<<<< * beta=&beta, y=&dL[k + 1, k], incy=&N) * */ __pyx_f_5scipy_6linalg_11cython_blas_dsymv(((char *)"u"), (&__pyx_v_n), (&__pyx_v_alpha), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_6 * __pyx_v_dL.strides[0]) )) + __pyx_t_7)) )))), (&__pyx_v_N), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_L.data + __pyx_t_8 * __pyx_v_L.strides[0]) )) + __pyx_t_9)) )))), (&__pyx_v_incx), (&__pyx_v_beta), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_10 * __pyx_v_dL.strides[0]) )) + __pyx_t_11)) )))), (&__pyx_v_N)); /* "GPy/util/choleskies_cython.pyx":101 * beta=&beta, y=&dL[k + 1, k], incy=&N) * * for i in xrange(0, N - k - 1): # <<<<<<<<<<<<<< * dL[k + 1 + i, k] -= dL[k + i+ 1, k + i + 1] * L[k + 1 + i, k] * */ __pyx_t_12 = ((__pyx_v_N - __pyx_v_k) - 1); __pyx_t_13 = __pyx_t_12; for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { __pyx_v_i = __pyx_t_14; /* "GPy/util/choleskies_cython.pyx":102 * * for i in xrange(0, N - k - 1): * dL[k + 1 + i, k] -= dL[k + i+ 1, k + i + 1] * L[k + 1 + i, k] # <<<<<<<<<<<<<< * * scale = 1.0 / L[k, k] */ __pyx_t_15 = ((__pyx_v_k + __pyx_v_i) + 1); __pyx_t_16 = ((__pyx_v_k + __pyx_v_i) + 1); if (__pyx_t_15 < 0) __pyx_t_15 += __pyx_v_dL.shape[0]; if (__pyx_t_16 < 0) __pyx_t_16 += __pyx_v_dL.shape[1]; __pyx_t_17 = ((__pyx_v_k + 1) + __pyx_v_i); __pyx_t_18 = __pyx_v_k; if (__pyx_t_17 < 0) __pyx_t_17 += __pyx_v_L.shape[0]; if (__pyx_t_18 < 0) __pyx_t_18 += __pyx_v_L.shape[1]; __pyx_t_19 = ((__pyx_v_k + 1) + __pyx_v_i); __pyx_t_20 = __pyx_v_k; if (__pyx_t_19 < 0) __pyx_t_19 += __pyx_v_dL.shape[0]; if (__pyx_t_20 < 0) __pyx_t_20 += __pyx_v_dL.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_19 * __pyx_v_dL.strides[0]) )) + __pyx_t_20)) )) -= ((*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_15 * __pyx_v_dL.strides[0]) )) + __pyx_t_16)) ))) * (*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_L.data + __pyx_t_17 * __pyx_v_L.strides[0]) )) + __pyx_t_18)) )))); } /* "GPy/util/choleskies_cython.pyx":104 * dL[k + 1 + i, k] -= dL[k + i+ 1, k + i + 1] * L[k + 1 + i, k] * * scale = 1.0 / L[k, k] # <<<<<<<<<<<<<< * cblas.dscal(&n, &scale , &dL[k + 1, k], &N) * # */ __pyx_t_21 = __pyx_v_k; __pyx_t_22 = __pyx_v_k; if (__pyx_t_21 < 0) __pyx_t_21 += __pyx_v_L.shape[0]; if (__pyx_t_22 < 0) __pyx_t_22 += __pyx_v_L.shape[1]; __pyx_t_23 = (*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_L.data + __pyx_t_21 * __pyx_v_L.strides[0]) )) + __pyx_t_22)) ))); if (unlikely(__pyx_t_23 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif __PYX_ERR(0, 104, __pyx_L1_error) } __pyx_v_scale = (1.0 / __pyx_t_23); /* "GPy/util/choleskies_cython.pyx":105 * * scale = 1.0 / L[k, k] * cblas.dscal(&n, &scale , &dL[k + 1, k], &N) # <<<<<<<<<<<<<< * # * dL[k, k] -= cblas.ddot(&n, &dL[k + 1, k], &N, &L[k+1, k], &incx) */ __pyx_t_24 = (__pyx_v_k + 1); __pyx_t_25 = __pyx_v_k; if (__pyx_t_24 < 0) __pyx_t_24 += __pyx_v_dL.shape[0]; if (__pyx_t_25 < 0) __pyx_t_25 += __pyx_v_dL.shape[1]; __pyx_f_5scipy_6linalg_11cython_blas_dscal((&__pyx_v_n), (&__pyx_v_scale), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_24 * __pyx_v_dL.strides[0]) )) + __pyx_t_25)) )))), (&__pyx_v_N)); /* "GPy/util/choleskies_cython.pyx":107 * cblas.dscal(&n, &scale , &dL[k + 1, k], &N) * # * dL[k, k] -= cblas.ddot(&n, &dL[k + 1, k], &N, &L[k+1, k], &incx) # <<<<<<<<<<<<<< * dL[k, k] /= (2.0 * L[k, k]) * */ __pyx_t_26 = (__pyx_v_k + 1); __pyx_t_27 = __pyx_v_k; if (__pyx_t_26 < 0) __pyx_t_26 += __pyx_v_dL.shape[0]; if (__pyx_t_27 < 0) __pyx_t_27 += __pyx_v_dL.shape[1]; __pyx_t_28 = (__pyx_v_k + 1); __pyx_t_29 = __pyx_v_k; if (__pyx_t_28 < 0) __pyx_t_28 += __pyx_v_L.shape[0]; if (__pyx_t_29 < 0) __pyx_t_29 += __pyx_v_L.shape[1]; __pyx_t_30 = __pyx_v_k; __pyx_t_31 = __pyx_v_k; if (__pyx_t_30 < 0) __pyx_t_30 += __pyx_v_dL.shape[0]; if (__pyx_t_31 < 0) __pyx_t_31 += __pyx_v_dL.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_30 * __pyx_v_dL.strides[0]) )) + __pyx_t_31)) )) -= __pyx_f_5scipy_6linalg_11cython_blas_ddot((&__pyx_v_n), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_26 * __pyx_v_dL.strides[0]) )) + __pyx_t_27)) )))), (&__pyx_v_N), (&(*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_L.data + __pyx_t_28 * __pyx_v_L.strides[0]) )) + __pyx_t_29)) )))), (&__pyx_v_incx)); /* "GPy/util/choleskies_cython.pyx":108 * # * dL[k, k] -= cblas.ddot(&n, &dL[k + 1, k], &N, &L[k+1, k], &incx) * dL[k, k] /= (2.0 * L[k, k]) # <<<<<<<<<<<<<< * * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): */ __pyx_t_32 = __pyx_v_k; __pyx_t_33 = __pyx_v_k; if (__pyx_t_32 < 0) __pyx_t_32 += __pyx_v_L.shape[0]; if (__pyx_t_33 < 0) __pyx_t_33 += __pyx_v_L.shape[1]; __pyx_t_34 = __pyx_v_k; __pyx_t_35 = __pyx_v_k; if (__pyx_t_34 < 0) __pyx_t_34 += __pyx_v_dL.shape[0]; if (__pyx_t_35 < 0) __pyx_t_35 += __pyx_v_dL.shape[1]; *((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_dL.data + __pyx_t_34 * __pyx_v_dL.strides[0]) )) + __pyx_t_35)) )) /= (2.0 * (*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_L.data + __pyx_t_32 * __pyx_v_L.strides[0]) )) + __pyx_t_33)) )))); } /* "GPy/util/choleskies_cython.pyx":85 * return dL_dK * * cdef void chol_backprop(int N, double[:, ::1] dL, double[:, ::1] L) nogil: # <<<<<<<<<<<<<< * cdef int i, k, n * */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __Pyx_WriteUnraisable("GPy.util.choleskies_cython.chol_backprop", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 1); __pyx_L0:; } /* "GPy/util/choleskies_cython.pyx":110 * dL[k, k] /= (2.0 * L[k, k]) * * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) */ /* Python wrapper */ static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_9backprop_gradient_par_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_3GPy_4util_17choleskies_cython_9backprop_gradient_par_c = {"backprop_gradient_par_c", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_3GPy_4util_17choleskies_cython_9backprop_gradient_par_c, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3GPy_4util_17choleskies_cython_9backprop_gradient_par_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_dL = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_L = { 0, 0, { 0 }, { 0 }, { 0 } }; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("backprop_gradient_par_c (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_dL,&__pyx_n_s_L,0}; PyObject* values[2] = {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 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dL)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_L)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("backprop_gradient_par_c", 1, 2, 2, 1); __PYX_ERR(0, 110, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "backprop_gradient_par_c") < 0)) __PYX_ERR(0, 110, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_dL = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_dL.memview)) __PYX_ERR(0, 110, __pyx_L3_error) __pyx_v_L = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_L.memview)) __PYX_ERR(0, 110, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("backprop_gradient_par_c", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 110, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("GPy.util.choleskies_cython.backprop_gradient_par_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3GPy_4util_17choleskies_cython_8backprop_gradient_par_c(__pyx_self, __pyx_v_dL, __pyx_v_L); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3GPy_4util_17choleskies_cython_8backprop_gradient_par_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_dL, __Pyx_memviewslice __pyx_v_L) { __Pyx_memviewslice __pyx_v_dL_dK = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_L_cont = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_v_N; 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; __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_RefNannySetupContext("backprop_gradient_par_c", 0); /* "GPy/util/choleskies_cython.pyx":111 * * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig # <<<<<<<<<<<<<< * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) * cdef int N = L.shape[0] */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_tril); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_dL, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1, PyBUF_WRITABLE); if (unlikely(!__pyx_t_5.memview)) __PYX_ERR(0, 111, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_dL_dK = __pyx_t_5; __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; /* "GPy/util/choleskies_cython.pyx":112 * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) # <<<<<<<<<<<<<< * cdef int N = L.shape[0] * with nogil: */ __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_L, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(__pyx_t_1, PyBUF_WRITABLE); if (unlikely(!__pyx_t_5.memview)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_L_cont = __pyx_t_5; __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; /* "GPy/util/choleskies_cython.pyx":113 * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) * cdef int N = L.shape[0] # <<<<<<<<<<<<<< * with nogil: * chol_backprop(N, dL_dK, L_cont) */ __pyx_v_N = (__pyx_v_L.shape[0]); /* "GPy/util/choleskies_cython.pyx":114 * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) * cdef int N = L.shape[0] * with nogil: # <<<<<<<<<<<<<< * chol_backprop(N, dL_dK, L_cont) * return np.asarray(dL_dK) */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { /* "GPy/util/choleskies_cython.pyx":115 * cdef int N = L.shape[0] * with nogil: * chol_backprop(N, dL_dK, L_cont) # <<<<<<<<<<<<<< * return np.asarray(dL_dK) */ __pyx_f_3GPy_4util_17choleskies_cython_chol_backprop(__pyx_v_N, __pyx_v_dL_dK, __pyx_v_L_cont); } /* "GPy/util/choleskies_cython.pyx":114 * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) * cdef int N = L.shape[0] * with nogil: # <<<<<<<<<<<<<< * chol_backprop(N, dL_dK, L_cont) * return np.asarray(dL_dK) */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "GPy/util/choleskies_cython.pyx":116 * with nogil: * chol_backprop(N, dL_dK, L_cont) * return np.asarray(dL_dK) # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 116, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_asarray); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 116, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_dL_dK, 2, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 116, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 116, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "GPy/util/choleskies_cython.pyx":110 * dL[k, k] /= (2.0 * L[k, k]) * * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) */ /* 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_XDEC_MEMVIEW(&__pyx_t_5, 1); __Pyx_AddTraceback("GPy.util.choleskies_cython.backprop_gradient_par_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_dL_dK, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_L_cont, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_dL, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_L, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 * # 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 fulfill 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_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_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; int __pyx_t_6; PyArray_Descr *__pyx_t_7; PyObject *__pyx_t_8 = NULL; char *__pyx_t_9; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * * cdef int i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * cdef int 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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * ndim = PyArray_NDIM(self) * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_ARRAY_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_L4_bool_binop_done; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_ARRAY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * ndim = PyArray_NDIM(self) * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ if (unlikely(__pyx_t_1)) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_ARRAY_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_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 272, __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_ERR(1, 272, __pyx_L1_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * ndim = PyArray_NDIM(self) * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_ARRAY_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_L7_bool_binop_done; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":275 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_ARRAY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L7_bool_binop_done:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ if (unlikely(__pyx_t_1)) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_ARRAY_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__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 276, __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_ERR(1, 276, __pyx_L1_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":279 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * 2) * ((size_t)__pyx_v_ndim)))); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":284 * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) * 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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":285 * info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) * 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; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * 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]); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":287 * 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]); } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ goto __pyx_L9; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * 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 */ /*else*/ { __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * 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_L9:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * 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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 * 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)); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":296 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = <dtype>PyArray_DESCR(self) * cdef int offset */ __pyx_v_f = NULL; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":297 * cdef int t * cdef char* f = NULL * cdef dtype descr = <dtype>PyArray_DESCR(self) # <<<<<<<<<<<<<< * cdef int offset * */ __pyx_t_7 = PyArray_DESCR(__pyx_v_self); __pyx_t_3 = ((PyObject *)__pyx_t_7); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":300 * cdef int offset * * info.obj = self # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(descr): */ __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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":302 * info.obj = self * * if not PyDataType_HASFIELDS(descr): # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(PyDataType_HASFIELDS(__pyx_v_descr) != 0)) != 0); if (__pyx_t_1) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":303 * * if not PyDataType_HASFIELDS(descr): * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":304 * if not PyDataType_HASFIELDS(descr): * 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_L15_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L14_bool_binop_done; } __pyx_L15_next_or:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":305 * 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_L14_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L14_bool_binop_done:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":304 * if not PyDataType_HASFIELDS(descr): * 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 (unlikely(__pyx_t_1)) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":306 * 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__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 306, __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_ERR(1, 306, __pyx_L1_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":304 * if not PyDataType_HASFIELDS(descr): * 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") */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":307 * (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" */ switch (__pyx_v_t) { case NPY_BYTE: __pyx_v_f = ((char *)"b"); break; case NPY_UBYTE: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":308 * 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" */ __pyx_v_f = ((char *)"B"); break; case NPY_SHORT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":309 * 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" */ __pyx_v_f = ((char *)"h"); break; case NPY_USHORT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":310 * 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" */ __pyx_v_f = ((char *)"H"); break; case NPY_INT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":311 * 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" */ __pyx_v_f = ((char *)"i"); break; case NPY_UINT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":312 * 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" */ __pyx_v_f = ((char *)"I"); break; case NPY_LONG: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":313 * 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" */ __pyx_v_f = ((char *)"l"); break; case NPY_ULONG: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":314 * 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" */ __pyx_v_f = ((char *)"L"); break; case NPY_LONGLONG: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":315 * 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" */ __pyx_v_f = ((char *)"q"); break; case NPY_ULONGLONG: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":316 * 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" */ __pyx_v_f = ((char *)"Q"); break; case NPY_FLOAT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":317 * 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" */ __pyx_v_f = ((char *)"f"); break; case NPY_DOUBLE: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":318 * 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" */ __pyx_v_f = ((char *)"d"); break; case NPY_LONGDOUBLE: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":319 * 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" */ __pyx_v_f = ((char *)"g"); break; case NPY_CFLOAT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":320 * 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" */ __pyx_v_f = ((char *)"Zf"); break; case NPY_CDOUBLE: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":321 * 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" */ __pyx_v_f = ((char *)"Zd"); break; case NPY_CLONGDOUBLE: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":322 * 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: */ __pyx_v_f = ((char *)"Zg"); break; case NPY_OBJECT: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":323 * 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) */ __pyx_v_f = ((char *)"O"); break; default: /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":325 * 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_ERR(1, 325, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 325, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 325, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 325, __pyx_L1_error) break; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":326 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":327 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>PyObject_Malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":302 * info.obj = self * * if not PyDataType_HASFIELDS(descr): # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":329 * return * else: * info.format = <char*>PyObject_Malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ /*else*/ { __pyx_v_info->format = ((char *)PyObject_Malloc(0xFF)); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":330 * else: * info.format = <char*>PyObject_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]) = '^'; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":331 * info.format = <char*>PyObject_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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":332 * 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_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(1, 332, __pyx_L1_error) __pyx_v_f = __pyx_t_9; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":335 * 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'; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 * # 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 fulfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":337 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * PyObject_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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":338 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":339 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * PyObject_Free(info.strides) */ PyObject_Free(__pyx_v_info->format); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":338 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":340 * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * PyObject_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) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":341 * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * PyObject_Free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ PyObject_Free(__pyx_v_info->strides); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":340 * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * PyObject_Free(info.strides) * # info.shape was stored after info.strides in the same block */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":337 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * 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; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * * 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_ERR(1, 822, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * 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; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":824 * 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; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 * * 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_ERR(1, 825, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":824 * 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; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * 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; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 * * 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_ERR(1, 828, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * 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; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * 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; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 * * 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_ERR(1, 831, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * 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; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * 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; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 * * 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 tuple PyDataType_SHAPE(dtype d): */ __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_ERR(1, 834, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * 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; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); if (__pyx_t_1) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape # <<<<<<<<<<<<<< * else: * return () */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * return <tuple>d.subarray.shape * else: * return () # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_empty_tuple); __pyx_r = __pyx_empty_tuple; goto __pyx_L0; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * return () * * 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; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":847 * * cdef dtype child * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":848 * cdef dtype child * 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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":851 * 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_ERR(1, 851, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(1, 851, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 851, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":852 * * 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_ERR(1, 852, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 852, __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_ERR(1, 852, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":853 * 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; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 853, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(1, 853, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 853, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 853, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 853, __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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":855 * 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_ERR(1, 855, __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_ERR(1, 855, __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_ERR(1, 855, __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 (unlikely(__pyx_t_6)) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":856 * * 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__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 856, __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_ERR(1, 856, __pyx_L1_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":855 * 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") * */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":858 * 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:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":859 * * 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:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":858 * 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") */ if (unlikely(__pyx_t_6)) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":860 * 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__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 860, __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_ERR(1, 860, __pyx_L1_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":858 * 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") */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":870 * * # 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_ERR(1, 870, __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_ERR(1, 870, __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_ERR(1, 870, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":871 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":872 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":873 * 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); } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":875 * 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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":877 * 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) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":878 * * 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_ERR(1, 878, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":879 * 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 (unlikely(__pyx_t_6)) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":880 * 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__5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 880, __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_ERR(1, 880, __pyx_L1_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":879 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":883 * * # 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 883, __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_ERR(1, 883, __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_ERR(1, 883, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":884 * # 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 884, __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_ERR(1, 884, __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_ERR(1, 884, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":885 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 885, __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_ERR(1, 885, __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_ERR(1, 885, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":886 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 886, __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_ERR(1, 886, __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_ERR(1, 886, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":887 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 887, __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_ERR(1, 887, __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_ERR(1, 887, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":888 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 888, __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_ERR(1, 888, __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_ERR(1, 888, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":889 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 889, __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_ERR(1, 889, __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_ERR(1, 889, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":890 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 890, __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_ERR(1, 890, __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_ERR(1, 890, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":891 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 891, __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_ERR(1, 891, __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_ERR(1, 891, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":892 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 892, __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_ERR(1, 892, __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_ERR(1, 892, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":893 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 893, __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_ERR(1, 893, __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_ERR(1, 893, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":894 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 894, __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_ERR(1, 894, __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_ERR(1, 894, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":895 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 895, __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_ERR(1, 895, __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_ERR(1, 895, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":896 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 896, __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_ERR(1, 896, __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_ERR(1, 896, __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]) = 0x66; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":897 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 897, __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_ERR(1, 897, __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_ERR(1, 897, __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]) = 0x64; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":898 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 898, __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_ERR(1, 898, __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_ERR(1, 898, __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]) = 0x67; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":899 * 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 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 899, __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_ERR(1, 899, __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_ERR(1, 899, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (likely(__pyx_t_6)) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":901 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ /*else*/ { __pyx_t_3 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 901, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 901, __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_ERR(1, 901, __pyx_L1_error) } __pyx_L15:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":902 * 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); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":877 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":906 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ /*else*/ { __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 == ((char *)NULL))) __PYX_ERR(1, 906, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":851 * 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; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":907 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * return () * * 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; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1022 * int _import_umath() except -1 * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1023 * * cdef inline void set_array_base(ndarray arr, object base): * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<< * PyArray_SetBaseObject(arr, base) * */ Py_INCREF(__pyx_v_base); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1024 * cdef inline void set_array_base(ndarray arr, object base): * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base)); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1022 * int _import_umath() except -1 * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1026 * PyArray_SetBaseObject(arr, base) * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * base = PyArray_BASE(arr) * if base is NULL: */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_v_base; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1027 * * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) # <<<<<<<<<<<<<< * if base is NULL: * return None */ __pyx_v_base = PyArray_BASE(__pyx_v_arr); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1028 * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) * if base is NULL: # <<<<<<<<<<<<<< * return None * return <object>base */ __pyx_t_1 = ((__pyx_v_base == NULL) != 0); if (__pyx_t_1) { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1029 * base = PyArray_BASE(arr) * if base is NULL: * return None # <<<<<<<<<<<<<< * return <object>base * */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1028 * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) * if base is NULL: # <<<<<<<<<<<<<< * return None * return <object>base */ } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1030 * if base is NULL: * return None * return <object>base # <<<<<<<<<<<<<< * * # Versions of the import_* functions which are more suitable for */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_base)); __pyx_r = ((PyObject *)__pyx_v_base); goto __pyx_L0; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1026 * PyArray_SetBaseObject(arr, base) * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * base = PyArray_BASE(arr) * if base is NULL: */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1034 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_array", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1035 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1036 * cdef inline int import_array() except -1: * try: * _import_array() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.multiarray failed to import") */ __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1036, __pyx_L3_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1035 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1037 * try: * _import_array() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.multiarray failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1037, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1038 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1038, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1038, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1035 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1034 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1040 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_umath", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1041 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1042 * cdef inline int import_umath() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1042, __pyx_L3_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1041 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1043 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1043, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1044 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1044, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1044, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1041 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1040 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1046 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_ufunc", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1047 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1048 * cdef inline int import_ufunc() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1048, __pyx_L3_error) /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1047 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1049 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1049, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1050 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1050, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1050, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1047 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1046 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":122 * 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_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); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(2, 122, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(2, 122, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 4: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__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_ERR(2, 122, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; 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_ERR(2, 122, __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_ERR(2, 123, __pyx_L3_error) } else { /* "View.MemoryView":123 * * 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_ERR(2, 122, __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_ERR(2, 122, __pyx_L1_error) if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(2, 122, __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":122 * 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; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; int __pyx_t_8; Py_ssize_t __pyx_t_9; PyObject *__pyx_t_10 = NULL; Py_ssize_t __pyx_t_11; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); /* "View.MemoryView":129 * 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_ERR(2, 129, __pyx_L1_error) } __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(2, 129, __pyx_L1_error) __pyx_v_self->ndim = ((int)__pyx_t_1); /* "View.MemoryView":130 * * self.ndim = <int> len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< * * if not self.ndim: */ __pyx_v_self->itemsize = __pyx_v_itemsize; /* "View.MemoryView":132 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":133 * * 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__8, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 133, __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_ERR(2, 133, __pyx_L1_error) /* "View.MemoryView":132 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ } /* "View.MemoryView":135 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":136 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 136, __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_ERR(2, 136, __pyx_L1_error) /* "View.MemoryView":135 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ } /* "View.MemoryView":138 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ __pyx_t_2 = PyBytes_Check(__pyx_v_format); __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":139 * * if not isinstance(format, bytes): * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 139, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); } } __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 139, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":138 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ } /* "View.MemoryView":140 * if not isinstance(format, bytes): * format = 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_ERR(2, 140, __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":141 * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ if (unlikely(__pyx_v_self->_format == Py_None)) { PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); __PYX_ERR(2, 141, __pyx_L1_error) } __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(2, 141, __pyx_L1_error) __pyx_v_self->format = __pyx_t_7; /* "View.MemoryView":144 * * * self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< * self._strides = self._shape + self.ndim * */ __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); /* "View.MemoryView":145 * * self._shape = <Py_ssize_t *> PyObject_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":147 * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":148 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 148, __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_ERR(2, 148, __pyx_L1_error) /* "View.MemoryView":147 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ } /* "View.MemoryView":151 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ __pyx_t_8 = 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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(2, 151, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 151, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_dim = __pyx_t_9; __pyx_v_idx = __pyx_t_8; __pyx_t_8 = (__pyx_t_8 + 1); /* "View.MemoryView":152 * * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":153 * 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_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(2, 153, __pyx_L1_error) /* "View.MemoryView":152 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ } /* "View.MemoryView":154 * 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":151 * * * 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":157 * * 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_ERR(2, 157, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":158 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< * self.mode = u'fortran' * elif mode == 'c': */ __pyx_v_order = 'F'; /* "View.MemoryView":159 * 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; /* "View.MemoryView":157 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ goto __pyx_L10; } /* "View.MemoryView":160 * 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_ERR(2, 160, __pyx_L1_error) if (likely(__pyx_t_4)) { /* "View.MemoryView":161 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< * self.mode = u'c' * else: */ __pyx_v_order = 'C'; /* "View.MemoryView":162 * 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; /* "View.MemoryView":160 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ goto __pyx_L10; } /* "View.MemoryView":164 * 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, */ /*else*/ { __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 164, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 164, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(2, 164, __pyx_L1_error) } __pyx_L10:; /* "View.MemoryView":166 * 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":169 * 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":170 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 170, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 170, __pyx_L1_error) __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; /* "View.MemoryView":171 * 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":174 * * * 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":175 * * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":176 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(2, 176, __pyx_L1_error) /* "View.MemoryView":175 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ } /* "View.MemoryView":178 * 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":179 * * 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":180 * 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)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(2, 180, __pyx_L1_error) } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(2, 180, __pyx_L1_error) } __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); __pyx_t_9 = __pyx_t_1; for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { __pyx_v_i = __pyx_t_11; /* "View.MemoryView":181 * 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":182 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * @cname('getbuffer') */ Py_INCREF(Py_None); } /* "View.MemoryView":178 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ } /* "View.MemoryView":171 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":122 * 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_5); __Pyx_XDECREF(__pyx_t_6); __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":185 * * @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; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "View.MemoryView":186 * @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":187 * 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_ERR(2, 187, __pyx_L1_error) __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":188 * 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); /* "View.MemoryView":187 * 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": */ goto __pyx_L3; } /* "View.MemoryView":189 * 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_ERR(2, 189, __pyx_L1_error) __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":190 * 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); /* "View.MemoryView":189 * 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_L3:; /* "View.MemoryView":191 * 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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":192 * 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__12, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 192, __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_ERR(2, 192, __pyx_L1_error) /* "View.MemoryView":191 * 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 */ } /* "View.MemoryView":193 * 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":194 * 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":195 * 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":196 * 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":197 * 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":198 * 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":199 * 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":200 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->readonly = 0; /* "View.MemoryView":202 * 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":203 * * 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; /* "View.MemoryView":202 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ goto __pyx_L5; } /* "View.MemoryView":205 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L5:; /* "View.MemoryView":207 * 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":185 * * @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->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":211 * __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":212 * * 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":213 * 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); /* "View.MemoryView":212 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ goto __pyx_L3; } /* "View.MemoryView":214 * 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":215 * 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":216 * 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); /* "View.MemoryView":215 * 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) */ } /* "View.MemoryView":218 * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) * free(self.data) # <<<<<<<<<<<<<< * PyObject_Free(self._shape) * */ free(__pyx_v_self->data); /* "View.MemoryView":214 * 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_L3:; /* "View.MemoryView":219 * self._strides, self.ndim, False) * free(self.data) * PyObject_Free(self._shape) # <<<<<<<<<<<<<< * * @property */ PyObject_Free(__pyx_v_self->_shape); /* "View.MemoryView":211 * __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":222 * * @property * def memview(self): # <<<<<<<<<<<<<< * return self.get_memview() * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(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) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":223 * @property * def memview(self): * return self.get_memview() # <<<<<<<<<<<<<< * * @cname('get_memview') */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 223, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":222 * * @property * def memview(self): # <<<<<<<<<<<<<< * return self.get_memview() * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __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":226 * * @cname('get_memview') * cdef get_memview(self): # <<<<<<<<<<<<<< * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) */ static PyObject *__pyx_array_get_memview(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; __Pyx_RefNannySetupContext("get_memview", 0); /* "View.MemoryView":227 * @cname('get_memview') * cdef get_memview(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":228 * cdef get_memview(self): * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * * def __len__(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 228, __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_ERR(2, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 228, __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":226 * * @cname('get_memview') * cdef get_memview(self): # <<<<<<<<<<<<<< * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) */ /* 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.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":230 * return memoryview(self, flags, self.dtype_is_object) * * def __len__(self): # <<<<<<<<<<<<<< * return self._shape[0] * */ /* Python wrapper */ static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__", 0); /* "View.MemoryView":231 * * def __len__(self): * return self._shape[0] # <<<<<<<<<<<<<< * * def __getattr__(self, attr): */ __pyx_r = (__pyx_v_self->_shape[0]); goto __pyx_L0; /* "View.MemoryView":230 * return memoryview(self, flags, self.dtype_is_object) * * def __len__(self): # <<<<<<<<<<<<<< * return self._shape[0] * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":233 * return self._shape[0] * * 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_8__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_8__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; __Pyx_RefNannySetupContext("__getattr__", 0); /* "View.MemoryView":234 * * 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_ERR(2, 234, __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_ERR(2, 234, __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":233 * return self._shape[0] * * 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":236 * 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_10__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_10__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; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":237 * * 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_ERR(2, 237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 237, __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":236 * 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":239 * 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_12__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_12__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; __Pyx_RefNannySetupContext("__setitem__", 0); /* "View.MemoryView":240 * * 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_ERR(2, 240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(2, 240, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":239 * 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; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":244 * * @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; __Pyx_RefNannySetupContext("array_cwrapper", 0); /* "View.MemoryView":248 * 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":249 * * 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_ERR(2, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 249, __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_ERR(2, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 249, __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; /* "View.MemoryView":248 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ goto __pyx_L3; } /* "View.MemoryView":251 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ /*else*/ { __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 251, __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_ERR(2, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; /* "View.MemoryView":252 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(2, 252, __pyx_L1_error) /* "View.MemoryView":251 * 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 *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 251, __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":253 * 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":255 * 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":244 * * @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":281 * 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_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); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__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_ERR(2, 281, __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_ERR(2, 281, __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":282 * 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":281 * 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":283 * 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":284 * 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":283 * 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; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * cdef tuple state * cdef object _dict */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_v_state = 0; PyObject *__pyx_v__dict = 0; int __pyx_v_use_setstate; 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; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":5 * cdef object _dict * cdef bint use_setstate * state = (self.name,) # <<<<<<<<<<<<<< * _dict = getattr(self, '__dict__', None) * if _dict is not None: */ __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_self->name); __Pyx_GIVEREF(__pyx_v_self->name); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); __pyx_v_state = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":6 * cdef bint use_setstate * state = (self.name,) * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< * if _dict is not None: * state += (_dict,) */ __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v__dict = __pyx_t_1; __pyx_t_1 = 0; /* "(tree fragment)":7 * state = (self.name,) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< * state += (_dict,) * use_setstate = True */ __pyx_t_2 = (__pyx_v__dict != Py_None); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { /* "(tree fragment)":8 * _dict = getattr(self, '__dict__', None) * if _dict is not None: * state += (_dict,) # <<<<<<<<<<<<<< * use_setstate = True * else: */ __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v__dict); __Pyx_GIVEREF(__pyx_v__dict); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); __pyx_t_4 = 0; /* "(tree fragment)":9 * if _dict is not None: * state += (_dict,) * use_setstate = True # <<<<<<<<<<<<<< * else: * use_setstate = self.name is not None */ __pyx_v_use_setstate = 1; /* "(tree fragment)":7 * state = (self.name,) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< * state += (_dict,) * use_setstate = True */ goto __pyx_L3; } /* "(tree fragment)":11 * use_setstate = True * else: * use_setstate = self.name is not None # <<<<<<<<<<<<<< * if use_setstate: * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state */ /*else*/ { __pyx_t_3 = (__pyx_v_self->name != Py_None); __pyx_v_use_setstate = __pyx_t_3; } __pyx_L3:; /* "(tree fragment)":12 * else: * use_setstate = self.name is not None * if use_setstate: # <<<<<<<<<<<<<< * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: */ __pyx_t_3 = (__pyx_v_use_setstate != 0); if (__pyx_t_3) { /* "(tree fragment)":13 * use_setstate = self.name is not None * if use_setstate: * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) */ __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_INCREF(__pyx_int_184977713); __Pyx_GIVEREF(__pyx_int_184977713); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); __Pyx_INCREF(__pyx_v_state); __Pyx_GIVEREF(__pyx_v_state); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); __pyx_t_4 = 0; __pyx_t_1 = 0; __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "(tree fragment)":12 * else: * use_setstate = self.name is not None * if use_setstate: # <<<<<<<<<<<<<< * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: */ } /* "(tree fragment)":15 * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_INCREF(__pyx_int_184977713); __Pyx_GIVEREF(__pyx_int_184977713); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); __Pyx_INCREF(__pyx_v_state); __Pyx_GIVEREF(__pyx_v_state); PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); __pyx_t_5 = 0; __pyx_t_1 = 0; __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * cdef tuple state * cdef object _dict */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_state); __Pyx_XDECREF(__pyx_v__dict); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":16 * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":17 * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< */ if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(2, 17, __pyx_L1_error) __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":16 * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /* 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.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":298 * * @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":300 * 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":304 * * with cython.cdivision(True): * offset = aligned_p % alignment # <<<<<<<<<<<<<< * * if offset > 0: */ __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); /* "View.MemoryView":306 * 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":307 * * 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)); /* "View.MemoryView":306 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ } /* "View.MemoryView":309 * aligned_p += alignment - offset * * return <void *> aligned_p # <<<<<<<<<<<<<< * * */ __pyx_r = ((void *)__pyx_v_aligned_p); goto __pyx_L0; /* "View.MemoryView":298 * * @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":345 * 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_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); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(2, 345, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__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_ERR(2, 345, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; 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_ERR(2, 345, __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_ERR(2, 345, __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_ERR(2, 345, __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; __Pyx_RefNannySetupContext("__cinit__", 0); /* "View.MemoryView":346 * * 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":347 * 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":348 * 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 *)__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":349 * 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 == ((int)-1))) __PYX_ERR(2, 349, __pyx_L1_error) /* "View.MemoryView":350 * 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":351 * __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":352 * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * global __pyx_memoryview_thread_locks_used */ Py_INCREF(Py_None); /* "View.MemoryView":350 * 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) */ } /* "View.MemoryView":348 * 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: */ } /* "View.MemoryView":355 * * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 */ __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); if (__pyx_t_1) { /* "View.MemoryView":356 * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: */ __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); /* "View.MemoryView":357 * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< * if self.lock is NULL: * self.lock = PyThread_allocate_lock() */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); /* "View.MemoryView":355 * * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 */ } /* "View.MemoryView":358 * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: # <<<<<<<<<<<<<< * self.lock = PyThread_allocate_lock() * if self.lock is NULL: */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":359 * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< * if self.lock is NULL: * raise MemoryError */ __pyx_v_self->lock = PyThread_allocate_lock(); /* "View.MemoryView":360 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":361 * self.lock = PyThread_allocate_lock() * if self.lock is NULL: * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ PyErr_NoMemory(); __PYX_ERR(2, 361, __pyx_L1_error) /* "View.MemoryView":360 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ } /* "View.MemoryView":358 * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: # <<<<<<<<<<<<<< * self.lock = PyThread_allocate_lock() * if self.lock is NULL: */ } /* "View.MemoryView":363 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":364 * * if flags & PyBUF_FORMAT: * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< * else: * self.dtype_is_object = dtype_is_object */ __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L11_bool_binop_done; } __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); __pyx_t_1 = __pyx_t_2; __pyx_L11_bool_binop_done:; __pyx_v_self->dtype_is_object = __pyx_t_1; /* "View.MemoryView":363 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ goto __pyx_L10; } /* "View.MemoryView":366 * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( */ /*else*/ { __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; } __pyx_L10:; /* "View.MemoryView":368 * 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":370 * 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":345 * 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_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":372 * 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) { int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; PyThread_type_lock __pyx_t_6; PyThread_type_lock __pyx_t_7; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":373 * * 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":374 * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< * * cdef int i */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); /* "View.MemoryView":373 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * */ } /* "View.MemoryView":378 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: */ __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":379 * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 */ __pyx_t_3 = __pyx_memoryview_thread_locks_used; __pyx_t_4 = __pyx_t_3; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":380 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: */ __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); if (__pyx_t_2) { /* "View.MemoryView":381 * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); /* "View.MemoryView":382 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); if (__pyx_t_2) { /* "View.MemoryView":384 * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< * break * else: */ __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); /* "View.MemoryView":383 * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) * break */ (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; /* "View.MemoryView":382 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ } /* "View.MemoryView":385 * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) * break # <<<<<<<<<<<<<< * else: * PyThread_free_lock(self.lock) */ goto __pyx_L6_break; /* "View.MemoryView":380 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: */ } } /*else*/ { /* "View.MemoryView":387 * break * else: * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< * * cdef char *get_item_pointer(memoryview self, object index) except NULL: */ PyThread_free_lock(__pyx_v_self->lock); } __pyx_L6_break:; /* "View.MemoryView":378 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: */ } /* "View.MemoryView":372 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":389 * 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; __Pyx_RefNannySetupContext("get_item_pointer", 0); /* "View.MemoryView":391 * 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":393 * 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_ERR(2, 393, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 393, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 393, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 393, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 393, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 393, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #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(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(2, 393, __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":394 * * 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_ERR(2, 394, __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 == ((char *)NULL))) __PYX_ERR(2, 394, __pyx_L1_error) __pyx_v_itemp = __pyx_t_7; /* "View.MemoryView":393 * 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":396 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_itemp; goto __pyx_L0; /* "View.MemoryView":389 * 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":399 * * * 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; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":400 * * 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":401 * 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":400 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ } /* "View.MemoryView":403 * 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_ERR(2, 403, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(2, 403, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 403, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 403, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 403, __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":406 * * 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_ERR(2, 406, __pyx_L1_error) if (__pyx_t_2) { /* "View.MemoryView":407 * 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_ERR(2, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":406 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ } /* "View.MemoryView":409 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< * return self.convert_item_to_object(itemp) * */ /*else*/ { __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 == ((char *)NULL))) __PYX_ERR(2, 409, __pyx_L1_error) __pyx_v_itemp = __pyx_t_6; /* "View.MemoryView":410 * 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_ERR(2, 410, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":399 * * * 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":412 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") */ /* 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 int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); /* "View.MemoryView":413 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< * raise TypeError("Cannot assign to read-only memoryview") * */ __pyx_t_1 = (__pyx_v_self->view.readonly != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":414 * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< * * have_slices, index = _unellipsify(index, self.view.ndim) */ __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 414, __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_ERR(2, 414, __pyx_L1_error) /* "View.MemoryView":413 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< * raise TypeError("Cannot assign to read-only memoryview") * */ } /* "View.MemoryView":416 * raise TypeError("Cannot assign to read-only memoryview") * * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 416, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (likely(__pyx_t_2 != Py_None)) { PyObject* sequence = __pyx_t_2; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(2, 416, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 416, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 416, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 416, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_3; __pyx_t_3 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":418 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 418, __pyx_L1_error) if (__pyx_t_1) { /* "View.MemoryView":419 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 419, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_obj = __pyx_t_2; __pyx_t_2 = 0; /* "View.MemoryView":420 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 420, __pyx_L1_error) if (__pyx_t_1) { /* "View.MemoryView":421 * 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_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 421, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 421, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":420 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ goto __pyx_L5; } /* "View.MemoryView":423 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< * else: * self.setitem_indexed(index, value) */ /*else*/ { __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 423, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(2, 423, __pyx_L1_error) __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 423, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L5:; /* "View.MemoryView":418 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ goto __pyx_L4; } /* "View.MemoryView":425 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ /*else*/ { __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 425, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L4:; /* "View.MemoryView":412 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __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":427 * 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; __Pyx_RefNannySetupContext("is_slice", 0); __Pyx_INCREF(__pyx_v_obj); /* "View.MemoryView":428 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":429 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __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":430 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 430, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":431 * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | 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_ERR(2, 431, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); /* "View.MemoryView":430 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 430, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 430, __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; /* "View.MemoryView":429 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ } __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_L9_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":432 * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< * return None * */ __pyx_t_9 = __Pyx_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_ERR(2, 432, __pyx_L6_except_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":433 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< * * return obj */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(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:; /* "View.MemoryView":429 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ __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_L9_try_end:; } /* "View.MemoryView":428 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, */ } /* "View.MemoryView":435 * 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":427 * 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":437 * 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; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); /* "View.MemoryView":441 * 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_ERR(2, 441, __pyx_L1_error) /* "View.MemoryView":442 * * 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_ERR(2, 442, __pyx_L1_error) /* "View.MemoryView":443 * 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_ERR(2, 443, __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_ERR(2, 443, __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_ERR(2, 443, __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_ERR(2, 443, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":441 * 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 == ((int)-1))) __PYX_ERR(2, 441, __pyx_L1_error) /* "View.MemoryView":437 * 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":445 * 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[0x80]; 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; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); /* "View.MemoryView":447 * 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":452 * 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":454 * 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":455 * * 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":456 * 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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":457 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ PyErr_NoMemory(); __PYX_ERR(2, 457, __pyx_L1_error) /* "View.MemoryView":456 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ } /* "View.MemoryView":458 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< * else: * item = <void *> array */ __pyx_v_item = __pyx_v_tmp; /* "View.MemoryView":454 * 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: */ goto __pyx_L3; } /* "View.MemoryView":460 * item = tmp * else: * item = <void *> array # <<<<<<<<<<<<<< * * try: */ /*else*/ { __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; /* "View.MemoryView":462 * item = <void *> array * * try: # <<<<<<<<<<<<<< * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value */ /*try:*/ { /* "View.MemoryView":463 * * 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":464 * 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); /* "View.MemoryView":463 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ goto __pyx_L8; } /* "View.MemoryView":466 * (<PyObject **> item)[0] = <PyObject *> value * else: * self.assign_item_from_object(<char *> item, value) # <<<<<<<<<<<<<< * * */ /*else*/ { __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_ERR(2, 466, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L8:; /* "View.MemoryView":470 * * * 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":471 * * 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_ERR(2, 471, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":470 * * * 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, */ } /* "View.MemoryView":472 * 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":475 * 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; } __pyx_L6_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __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":445 * 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":477 * 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; __Pyx_RefNannySetupContext("setitem_indexed", 0); /* "View.MemoryView":478 * * 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 == ((char *)NULL))) __PYX_ERR(2, 478, __pyx_L1_error) __pyx_v_itemp = __pyx_t_1; /* "View.MemoryView":479 * 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_ERR(2, 479, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":477 * 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":481 * 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; int __pyx_t_8; PyObject *__pyx_t_9 = NULL; size_t __pyx_t_10; int __pyx_t_11; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":484 * """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, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 484, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":487 * 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_ERR(2, 487, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":488 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __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":489 * 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_ERR(2, 489, __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_ERR(2, 489, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && 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; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 489, __pyx_L3_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 489, __pyx_L3_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else #endif { __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 489, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_7) { __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; } __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); __Pyx_INCREF(__pyx_v_bytesitem); __Pyx_GIVEREF(__pyx_v_bytesitem); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __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_ERR(2, 489, __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; /* "View.MemoryView":488 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ } /* "View.MemoryView":493 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ /*else:*/ { __pyx_t_10 = strlen(__pyx_v_self->view.format); __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { /* "View.MemoryView":494 * 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, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 494, __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":493 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ } /* "View.MemoryView":495 * 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":490 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 490, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; if (__pyx_t_8) { __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(2, 490, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_1); /* "View.MemoryView":491 * 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__16, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 491, __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_ERR(2, 491, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "View.MemoryView":488 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.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":481 * 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":497 * 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; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; Py_ssize_t __pyx_t_9; PyObject *__pyx_t_10 = NULL; char *__pyx_t_11; char *__pyx_t_12; char *__pyx_t_13; char *__pyx_t_14; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":500 * """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, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 500, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":505 * 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":506 * * 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_ERR(2, 506, __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_ERR(2, 506, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 506, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 506, __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_ERR(2, 506, __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_ERR(2, 506, __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_ERR(2, 506, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":505 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ goto __pyx_L3; } /* "View.MemoryView":508 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< * * for i, c in enumerate(bytesvalue): */ /*else*/ { __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 508, __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_ERR(2, 508, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; if (CYTHON_UNPACK_METHODS && 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; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 508, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 508, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif { __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 508, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); if (__pyx_t_5) { __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; } __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_v_value); __Pyx_GIVEREF(__pyx_v_value); PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __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_ERR(2, 508, __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_ERR(2, 508, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; /* "View.MemoryView":510 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_9 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); __PYX_ERR(2, 510, __pyx_L1_error) } __Pyx_INCREF(__pyx_v_bytesvalue); __pyx_t_10 = __pyx_v_bytesvalue; __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { __pyx_t_11 = __pyx_t_14; __pyx_v_c = (__pyx_t_11[0]); /* "View.MemoryView":511 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ __pyx_v_i = __pyx_t_9; /* "View.MemoryView":510 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_9 = (__pyx_t_9 + 1); /* "View.MemoryView":511 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; } __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; /* "View.MemoryView":497 * 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_10); __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":514 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") */ /* 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; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; Py_ssize_t *__pyx_t_4; char *__pyx_t_5; void *__pyx_t_6; int __pyx_t_7; Py_ssize_t __pyx_t_8; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "View.MemoryView":515 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< * raise ValueError("Cannot create writable memory view from read-only memoryview") * */ __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L4_bool_binop_done; } __pyx_t_2 = (__pyx_v_self->view.readonly != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; if (unlikely(__pyx_t_1)) { /* "View.MemoryView":516 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< * * if flags & PyBUF_ND: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 516, __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_ERR(2, 516, __pyx_L1_error) /* "View.MemoryView":515 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< * raise ValueError("Cannot create writable memory view from read-only memoryview") * */ } /* "View.MemoryView":518 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); if (__pyx_t_1) { /* "View.MemoryView":519 * * if flags & PyBUF_ND: * info.shape = self.view.shape # <<<<<<<<<<<<<< * else: * info.shape = NULL */ __pyx_t_4 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_4; /* "View.MemoryView":518 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ goto __pyx_L6; } /* "View.MemoryView":521 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ /*else*/ { __pyx_v_info->shape = NULL; } __pyx_L6:; /* "View.MemoryView":523 * 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":524 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< * else: * info.strides = NULL */ __pyx_t_4 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_4; /* "View.MemoryView":523 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ goto __pyx_L7; } /* "View.MemoryView":526 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ /*else*/ { __pyx_v_info->strides = NULL; } __pyx_L7:; /* "View.MemoryView":528 * 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":529 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< * else: * info.suboffsets = NULL */ __pyx_t_4 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_4; /* "View.MemoryView":528 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ goto __pyx_L8; } /* "View.MemoryView":531 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ /*else*/ { __pyx_v_info->suboffsets = NULL; } __pyx_L8:; /* "View.MemoryView":533 * 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":534 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_5 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_5; /* "View.MemoryView":533 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ goto __pyx_L9; } /* "View.MemoryView":536 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L9:; /* "View.MemoryView":538 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize */ __pyx_t_6 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_6; /* "View.MemoryView":539 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< * info.itemsize = self.view.itemsize * info.len = self.view.len */ __pyx_t_7 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_7; /* "View.MemoryView":540 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< * info.len = self.view.len * info.readonly = self.view.readonly */ __pyx_t_8 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_8; /* "View.MemoryView":541 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< * info.readonly = self.view.readonly * info.obj = self */ __pyx_t_8 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_8; /* "View.MemoryView":542 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = self.view.readonly # <<<<<<<<<<<<<< * info.obj = self * */ __pyx_t_1 = __pyx_v_self->view.readonly; __pyx_v_info->readonly = __pyx_t_1; /* "View.MemoryView":543 * info.len = self.view.len * info.readonly = self.view.readonly * 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":514 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":549 * * @property * def T(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":550 * @property * def T(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_ERR(2, 550, __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_ERR(2, 550, __pyx_L1_error) __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":551 * def T(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 == ((int)0))) __PYX_ERR(2, 551, __pyx_L1_error) /* "View.MemoryView":552 * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) * return result # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":549 * * @property * def T(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":555 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(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":556 * @property * def base(self): * return self.obj # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->obj); __pyx_r = __pyx_v_self->obj; goto __pyx_L0; /* "View.MemoryView":555 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":559 * * @property * def shape(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":560 * @property * def shape(self): * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 560, __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_ERR(2, 560, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(2, 560, __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_ERR(2, 560, __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":559 * * @property * def shape(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":563 * * @property * def strides(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":564 * @property * def strides(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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":566 * 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__18, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 566, __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_ERR(2, 566, __pyx_L1_error) /* "View.MemoryView":564 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ } /* "View.MemoryView":568 * raise ValueError("Buffer view does not expose strides") * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 568, __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_ERR(2, 568, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(2, 568, __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_ERR(2, 568, __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":563 * * @property * def strides(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":571 * * @property * def suboffsets(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":572 * @property * def suboffsets(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":573 * def suboffsets(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_ERR(2, 573, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__19, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 573, __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":572 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ } /* "View.MemoryView":575 * return (-1,) * self.view.ndim * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 575, __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_ERR(2, 575, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(2, 575, __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_ERR(2, 575, __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":571 * * @property * def suboffsets(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":578 * * @property * def ndim(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":579 * @property * def ndim(self): * return self.view.ndim # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":578 * * @property * def ndim(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":582 * * @property * def itemsize(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":583 * @property * def itemsize(self): * return self.view.itemsize # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 583, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":582 * * @property * def itemsize(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":586 * * @property * def nbytes(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":587 * @property * def nbytes(self): * return self.size * self.view.itemsize # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 587, __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_ERR(2, 587, __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_ERR(2, 587, __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":586 * * @property * def nbytes(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":590 * * @property * def size(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(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; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":591 * @property * def size(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":592 * def size(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":594 * 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_ERR(2, 594, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; /* "View.MemoryView":595 * * 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_ERR(2, 595, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } /* "View.MemoryView":597 * 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; /* "View.MemoryView":591 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ } /* "View.MemoryView":599 * 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":590 * * @property * def size(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":601 * 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":602 * * 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":603 * 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":602 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ } /* "View.MemoryView":605 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< * * def __repr__(self): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":601 * 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":607 * 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; __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":608 * * 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_ERR(2, 608, __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_ERR(2, 608, __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_ERR(2, 608, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":609 * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 609, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); /* "View.MemoryView":608 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 608, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 608, __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":607 * 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":611 * 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; __Pyx_RefNannySetupContext("__str__", 0); /* "View.MemoryView":612 * * 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_ERR(2, 612, __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_ERR(2, 612, __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_ERR(2, 612, __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_ERR(2, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __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_ERR(2, 612, __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":611 * 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":615 * * * 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; __Pyx_RefNannySetupContext("is_c_contig", 0); /* "View.MemoryView":618 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice[0], 'C', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); /* "View.MemoryView":619 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], '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[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 619, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":615 * * * 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":621 * return slice_is_contig(mslice[0], '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; __Pyx_RefNannySetupContext("is_f_contig", 0); /* "View.MemoryView":624 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice[0], 'F', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); /* "View.MemoryView":625 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< * * def copy(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 625, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":621 * return slice_is_contig(mslice[0], '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":627 * return slice_is_contig(mslice[0], '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; __Pyx_RefNannySetupContext("copy", 0); /* "View.MemoryView":629 * 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":631 * 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":632 * * 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), ((char *)"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_ERR(2, 632, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":637 * 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_ERR(2, 637, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":627 * return slice_is_contig(mslice[0], '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":639 * 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; __Pyx_RefNannySetupContext("copy_fortran", 0); /* "View.MemoryView":641 * 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":643 * 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":644 * * 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), ((char *)"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_ERR(2, 644, __pyx_L1_error) __pyx_v_dst = __pyx_t_1; /* "View.MemoryView":649 * 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_ERR(2, 649, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":639 * 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; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":653 * * @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; __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); /* "View.MemoryView":654 * @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_ERR(2, 654, __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_ERR(2, 654, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 654, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 654, __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":655 * 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":656 * 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":653 * * @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":659 * * @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":660 * @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, __pyx_memoryview_type); __pyx_r = __pyx_t_1; goto __pyx_L0; /* "View.MemoryView":659 * * @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":662 * 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; __Pyx_RefNannySetupContext("_unellipsify", 0); /* "View.MemoryView":667 * 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":668 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 668, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; /* "View.MemoryView":667 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ goto __pyx_L3; } /* "View.MemoryView":670 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ /*else*/ { __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; /* "View.MemoryView":672 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 672, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":673 * * result = [] * have_slices = False # <<<<<<<<<<<<<< * seen_ellipsis = False * for idx, item in enumerate(tup): */ __pyx_v_have_slices = 0; /* "View.MemoryView":674 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< * for idx, item in enumerate(tup): * if item is Ellipsis: */ __pyx_v_seen_ellipsis = 0; /* "View.MemoryView":675 * 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_ERR(2, 675, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 675, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 675, __pyx_L1_error) #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 675, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 675, __pyx_L1_error) #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 675, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #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(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(2, 675, __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 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 675, __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":676 * 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":677 * 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":678 * 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 == ((Py_ssize_t)-1))) __PYX_ERR(2, 678, __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_ERR(2, 678, __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__22); __Pyx_GIVEREF(__pyx_slice__22); PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__22); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 678, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":679 * 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; /* "View.MemoryView":677 * 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 */ goto __pyx_L7; } /* "View.MemoryView":681 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ /*else*/ { __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__22); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 681, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":682 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< * else: * if not isinstance(item, slice) and not PyIndex_Check(item): */ __pyx_v_have_slices = 1; /* "View.MemoryView":676 * 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)) */ goto __pyx_L6; } /* "View.MemoryView":684 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ /*else*/ { __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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":685 * 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_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 685, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 685, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_Raise(__pyx_t_11, 0, 0, 0); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __PYX_ERR(2, 685, __pyx_L1_error) /* "View.MemoryView":684 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ } /* "View.MemoryView":687 * 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":688 * * 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 == ((int)-1))) __PYX_ERR(2, 688, __pyx_L1_error) } __pyx_L6:; /* "View.MemoryView":675 * 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":690 * 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 == ((Py_ssize_t)-1))) __PYX_ERR(2, 690, __pyx_L1_error) __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); /* "View.MemoryView":691 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { /* "View.MemoryView":692 * 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_ERR(2, 692, __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__22); __Pyx_GIVEREF(__pyx_slice__22); PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__22); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 692, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":691 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ } /* "View.MemoryView":694 * 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_ERR(2, 694, __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_ERR(2, 694, __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_ERR(2, 694, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 694, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_11); __pyx_t_11 = 0; goto __pyx_L0; /* "View.MemoryView":662 * 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":696 * 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; __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); /* "View.MemoryView":697 * * 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":698 * 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 (unlikely(__pyx_t_4)) { /* "View.MemoryView":699 * 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__23, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 699, __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_ERR(2, 699, __pyx_L1_error) /* "View.MemoryView":698 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ } } /* "View.MemoryView":696 * 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":706 * * @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; __Pyx_RefNannySetupContext("memview_slice", 0); /* "View.MemoryView":707 * @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":714 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< * * cdef _memoryviewslice memviewsliceobj */ (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); /* "View.MemoryView":718 * 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_ERR(2, 718, __pyx_L1_error) } } #endif /* "View.MemoryView":720 * 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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":721 * * 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_ERR(2, 721, __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":722 * 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); /* "View.MemoryView":720 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ goto __pyx_L3; } /* "View.MemoryView":724 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< * p_src = &src * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); /* "View.MemoryView":725 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< * * */ __pyx_v_p_src = (&__pyx_v_src); } __pyx_L3:; /* "View.MemoryView":731 * * * 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":732 * * 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":737 * * * 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":738 * * 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":742 * 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_ERR(2, 742, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 742, __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_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 742, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 742, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } else { if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __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_ERR(2, 742, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 742, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #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(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(2, 742, __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":743 * * 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":747 * 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_ERR(2, 747, __pyx_L1_error) /* "View.MemoryView":744 * 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 == ((int)-1))) __PYX_ERR(2, 744, __pyx_L1_error) /* "View.MemoryView":743 * * 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], */ goto __pyx_L6; } /* "View.MemoryView":750 * 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":751 * 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":752 * 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":753 * 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]) = -1L; /* "View.MemoryView":754 * 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); /* "View.MemoryView":750 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ goto __pyx_L6; } /* "View.MemoryView":756 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< * stop = index.stop or 0 * step = index.step or 0 */ /*else*/ { __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 756, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 756, __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_ERR(2, 756, __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":757 * 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_ERR(2, 757, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 757, __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_ERR(2, 757, __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":758 * 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_ERR(2, 758, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 758, __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_ERR(2, 758, __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":760 * 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_ERR(2, 760, __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":761 * * 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_ERR(2, 761, __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":762 * 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_ERR(2, 762, __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":764 * 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 == ((int)-1))) __PYX_ERR(2, 764, __pyx_L1_error) /* "View.MemoryView":770 * 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":742 * 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":772 * 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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":773 * * 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":774 * 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_ERR(2, 774, __pyx_L1_error) } /* "View.MemoryView":775 * 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_ERR(2, 775, __pyx_L1_error) } /* "View.MemoryView":773 * * 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_ERR(2, 773, __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_ERR(2, 773, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":772 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ } /* "View.MemoryView":778 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ /*else*/ { __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":779 * 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_ERR(2, 778, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":778 * 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_ERR(2, 778, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":706 * * @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":803 * * @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; /* "View.MemoryView":823 * 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":825 * 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":826 * * 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); /* "View.MemoryView":825 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ } /* "View.MemoryView":827 * 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":828 * 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, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 828, __pyx_L1_error) /* "View.MemoryView":827 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ } /* "View.MemoryView":823 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ goto __pyx_L3; } /* "View.MemoryView":831 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< * * if have_step and step == 0: */ /*else*/ { __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":833 * 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":834 * * 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, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 834, __pyx_L1_error) /* "View.MemoryView":833 * 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) * */ } /* "View.MemoryView":837 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { /* "View.MemoryView":838 * * 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":839 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< * if start < 0: * start = 0 */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":840 * 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":841 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< * elif start >= shape: * if negative_step: */ __pyx_v_start = 0; /* "View.MemoryView":840 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ } /* "View.MemoryView":838 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ goto __pyx_L12; } /* "View.MemoryView":842 * 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":843 * 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":844 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":843 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L14; } /* "View.MemoryView":846 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ /*else*/ { __pyx_v_start = __pyx_v_shape; } __pyx_L14:; /* "View.MemoryView":842 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ } __pyx_L12:; /* "View.MemoryView":837 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ goto __pyx_L11; } /* "View.MemoryView":848 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":849 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":848 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L15; } /* "View.MemoryView":851 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ /*else*/ { __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; /* "View.MemoryView":853 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { /* "View.MemoryView":854 * * 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":855 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< * if stop < 0: * stop = 0 */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); /* "View.MemoryView":856 * 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":857 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< * elif stop > shape: * stop = shape */ __pyx_v_stop = 0; /* "View.MemoryView":856 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ } /* "View.MemoryView":854 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ goto __pyx_L17; } /* "View.MemoryView":858 * 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":859 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_stop = __pyx_v_shape; /* "View.MemoryView":858 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ } __pyx_L17:; /* "View.MemoryView":853 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ goto __pyx_L16; } /* "View.MemoryView":861 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":862 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ __pyx_v_stop = -1L; /* "View.MemoryView":861 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ goto __pyx_L19; } /* "View.MemoryView":864 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ /*else*/ { __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; /* "View.MemoryView":866 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":867 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< * * */ __pyx_v_step = 1; /* "View.MemoryView":866 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ } /* "View.MemoryView":871 * * 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":873 * 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":874 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< * * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); /* "View.MemoryView":873 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ } /* "View.MemoryView":876 * 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":877 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< * * */ __pyx_v_new_shape = 0; /* "View.MemoryView":876 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ } /* "View.MemoryView":880 * * * 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":881 * * 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":882 * 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":885 * * * 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":886 * * 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)); /* "View.MemoryView":885 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ goto __pyx_L23; } /* "View.MemoryView":888 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< * * if suboffset >= 0: */ /*else*/ { __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":890 * 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":891 * * 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":892 * 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":893 * 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); /* "View.MemoryView":892 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ goto __pyx_L26; } /* "View.MemoryView":895 * dst.data = (<char **> dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< * "must be indexed and not sliced", dim) * else: */ /*else*/ { /* "View.MemoryView":896 * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< * else: * suboffset_dim[0] = new_ndim */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 895, __pyx_L1_error) } __pyx_L26:; /* "View.MemoryView":891 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ goto __pyx_L25; } /* "View.MemoryView":898 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< * * return 0 */ /*else*/ { (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; } __pyx_L25:; /* "View.MemoryView":890 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ } /* "View.MemoryView":900 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":803 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":906 * * @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; __Pyx_RefNannySetupContext("pybuffer_index", 0); /* "View.MemoryView":908 * 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 = -1L; /* "View.MemoryView":909 * 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":912 * 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":913 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< * stride = itemsize * else: */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(2, 913, __pyx_L1_error) } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(2, 913, __pyx_L1_error) } __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); /* "View.MemoryView":914 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< * else: * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; /* "View.MemoryView":912 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ goto __pyx_L3; } /* "View.MemoryView":916 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< * stride = view.strides[dim] * if view.suboffsets != NULL: */ /*else*/ { __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); /* "View.MemoryView":917 * 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":918 * 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":919 * 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]); /* "View.MemoryView":918 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ } } __pyx_L3:; /* "View.MemoryView":921 * 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":922 * * 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":923 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":924 * 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_ERR(2, 924, __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_ERR(2, 924, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 924, __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_ERR(2, 924, __pyx_L1_error) /* "View.MemoryView":923 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":921 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ } /* "View.MemoryView":926 * 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 (unlikely(__pyx_t_2)) { /* "View.MemoryView":927 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 927, __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_ERR(2, 927, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 927, __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_ERR(2, 927, __pyx_L1_error) /* "View.MemoryView":926 * 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) * */ } /* "View.MemoryView":929 * 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":930 * * 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":931 * 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); /* "View.MemoryView":930 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ } /* "View.MemoryView":933 * resultp = (<char **> resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_resultp; goto __pyx_L0; /* "View.MemoryView":906 * * @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":939 * * @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; long __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; /* "View.MemoryView":940 * @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":942 * 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":943 * * 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":947 * * 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); __pyx_t_4 = __pyx_t_3; for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":948 * 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":949 * 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_5 = (__pyx_v_strides[__pyx_v_j]); __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; /* "View.MemoryView":950 * 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_6 = (__pyx_v_shape[__pyx_v_j]); __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; /* "View.MemoryView":952 * 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_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); if (!__pyx_t_8) { } else { __pyx_t_7 = __pyx_t_8; goto __pyx_L6_bool_binop_done; } __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); __pyx_t_7 = __pyx_t_8; __pyx_L6_bool_binop_done:; if (__pyx_t_7) { /* "View.MemoryView":953 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 953, __pyx_L1_error) /* "View.MemoryView":952 * 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") * */ } } /* "View.MemoryView":955 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< * * */ __pyx_r = 1; goto __pyx_L0; /* "View.MemoryView":939 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":972 * 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":973 * * 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":972 * 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":975 * __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; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":976 * * 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":977 * 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_ERR(2, 977, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":976 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ } /* "View.MemoryView":979 * 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): */ /*else*/ { __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_ERR(2, 979, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /* "View.MemoryView":975 * __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":981 * 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; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":982 * * 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":983 * 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 == ((int)0))) __PYX_ERR(2, 983, __pyx_L1_error) /* "View.MemoryView":982 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ goto __pyx_L3; } /* "View.MemoryView":985 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< * * @property */ /*else*/ { __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_ERR(2, 985, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; /* "View.MemoryView":981 * 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":988 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(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":989 * @property * def base(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":988 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(2, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":995 * * @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; __Pyx_RefNannySetupContext("memoryview_fromslice", 0); /* "View.MemoryView":1003 * 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":1004 * * if <PyObject *> memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; /* "View.MemoryView":1003 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ } /* "View.MemoryView":1009 * * * 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_ERR(2, 1009, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1009, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1009, __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":1011 * 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":1012 * * 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":1014 * __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_ERR(2, 1014, __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":1015 * * 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":1017 * 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":1018 * * 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":1019 * 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":1020 * 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":1021 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: */ Py_INCREF(Py_None); /* "View.MemoryView":1023 * Py_INCREF(Py_None) * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< * result.flags = PyBUF_RECORDS * else: */ __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); if (__pyx_t_1) { /* "View.MemoryView":1024 * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< * else: * result.flags = PyBUF_RECORDS_RO */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; /* "View.MemoryView":1023 * Py_INCREF(Py_None) * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< * result.flags = PyBUF_RECORDS * else: */ goto __pyx_L4; } /* "View.MemoryView":1026 * result.flags = PyBUF_RECORDS * else: * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< * * result.view.shape = <Py_ssize_t *> result.from_slice.shape */ /*else*/ { __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; } __pyx_L4:; /* "View.MemoryView":1028 * result.flags = PyBUF_RECORDS_RO * * 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":1029 * * 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":1032 * * * 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":1033 * * 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":1034 * 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":1035 * 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":1036 * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ goto __pyx_L6_break; /* "View.MemoryView":1034 * 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_L6_break:; /* "View.MemoryView":1038 * 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":1039 * * 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_ERR(2, 1039, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":1040 * 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_ERR(2, 1040, __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_ERR(2, 1040, __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_ERR(2, 1040, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } /* "View.MemoryView":1042 * 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":1043 * * 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":1045 * 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":995 * * @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":1048 * * @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; __Pyx_RefNannySetupContext("get_slice_from_memview", 0); /* "View.MemoryView":1051 * __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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1052 * 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_ERR(2, 1052, __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":1053 * 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; /* "View.MemoryView":1051 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ } /* "View.MemoryView":1055 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); /* "View.MemoryView":1056 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_slice_copy') */ __pyx_r = __pyx_v_mslice; goto __pyx_L0; } /* "View.MemoryView":1048 * * @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, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1059 * * @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; int __pyx_t_4; Py_ssize_t __pyx_t_5; __Pyx_RefNannySetupContext("slice_copy", 0); /* "View.MemoryView":1063 * 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":1064 * * 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":1065 * 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":1067 * 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":1068 * * 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":1070 * 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; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_dim = __pyx_t_4; /* "View.MemoryView":1071 * * 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":1072 * 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":1073 * 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_5 = (__pyx_v_suboffsets[__pyx_v_dim]); } else { __pyx_t_5 = -1L; } (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; } /* "View.MemoryView":1059 * * @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":1076 * * @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; __Pyx_RefNannySetupContext("memoryview_copy", 0); /* "View.MemoryView":1079 * "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":1080 * 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_ERR(2, 1080, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":1076 * * @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":1083 * * @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; __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); /* "View.MemoryView":1090 * 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), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1091 * * 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":1092 * 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; /* "View.MemoryView":1090 * 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 */ goto __pyx_L3; } /* "View.MemoryView":1094 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< * to_dtype_func = NULL * */ /*else*/ { __pyx_v_to_object_func = NULL; /* "View.MemoryView":1095 * 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":1097 * 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":1099 * 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_ERR(2, 1097, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":1083 * * @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":1105 * * * 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":1106 * * 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":1107 * 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; /* "View.MemoryView":1106 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ } /* "View.MemoryView":1109 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ /*else*/ { __pyx_r = __pyx_v_arg; goto __pyx_L0; } /* "View.MemoryView":1105 * * * 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":1112 * * @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; int __pyx_t_4; /* "View.MemoryView":1117 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< * cdef Py_ssize_t f_stride = 0 * */ __pyx_v_c_stride = 0; /* "View.MemoryView":1118 * 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":1120 * 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":1121 * * 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":1122 * 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":1123 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * for i in range(ndim): */ goto __pyx_L4_break; /* "View.MemoryView":1121 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ } } __pyx_L4_break:; /* "View.MemoryView":1125 * break * * for i in range(ndim): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] */ __pyx_t_1 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_1; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1126 * * 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":1127 * 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":1128 * 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; /* "View.MemoryView":1126 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ } } __pyx_L7_break:; /* "View.MemoryView":1130 * 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":1131 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< * else: * return 'F' */ __pyx_r = 'C'; goto __pyx_L0; /* "View.MemoryView":1130 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ } /* "View.MemoryView":1133 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ /*else*/ { __pyx_r = 'F'; goto __pyx_L0; } /* "View.MemoryView":1112 * * @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":1136 * * @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; Py_ssize_t __pyx_t_6; /* "View.MemoryView":1143 * * 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":1144 * 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":1145 * 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":1146 * 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":1148 * 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":1149 * * 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":1150 * 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:; /* "View.MemoryView":1149 * * 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) */ if (__pyx_t_1) { /* "View.MemoryView":1151 * 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): */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); /* "View.MemoryView":1149 * * 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) */ goto __pyx_L4; } /* "View.MemoryView":1153 * 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 */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1154 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< * src_data += src_stride * dst_data += dst_stride */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); /* "View.MemoryView":1155 * 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":1156 * 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:; /* "View.MemoryView":1148 * 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): */ goto __pyx_L3; } /* "View.MemoryView":1158 * 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, */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1159 * 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":1163 * 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":1164 * 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":1136 * * @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":1166 * 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":1169 * __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":1166 * 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":1173 * * @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; int __pyx_t_4; /* "View.MemoryView":1176 * "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":1178 * cdef Py_ssize_t size = src.memview.view.itemsize * * for i in range(ndim): # <<<<<<<<<<<<<< * size *= src.shape[i] * */ __pyx_t_2 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1179 * * 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":1181 * size *= src.shape[i] * * return size # <<<<<<<<<<<<<< * * @cname('__pyx_fill_contig_strides_array') */ __pyx_r = __pyx_v_size; goto __pyx_L0; /* "View.MemoryView":1173 * * @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":1184 * * @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; int __pyx_t_4; /* "View.MemoryView":1193 * 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":1194 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ __pyx_t_2 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_idx = __pyx_t_4; /* "View.MemoryView":1195 * 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":1196 * 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])); } /* "View.MemoryView":1193 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ goto __pyx_L3; } /* "View.MemoryView":1198 * stride = stride * shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ /*else*/ { for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; /* "View.MemoryView":1199 * 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":1200 * 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":1202 * stride = stride * shape[idx] * * return stride # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_data_to_temp') */ __pyx_r = __pyx_v_stride; goto __pyx_L0; /* "View.MemoryView":1184 * * @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":1205 * * @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_t_6; /* "View.MemoryView":1216 * 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":1217 * * 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":1219 * 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":1220 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1221 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 1221, __pyx_L1_error) /* "View.MemoryView":1220 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ } /* "View.MemoryView":1224 * * * tmpslice.data = <char *> result # <<<<<<<<<<<<<< * tmpslice.memview = src.memview * for i in range(ndim): */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); /* "View.MemoryView":1225 * * 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":1226 * 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; __pyx_t_5 = __pyx_t_3; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1227 * 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":1228 * 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]) = -1L; } /* "View.MemoryView":1230 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< * ndim, order) * */ (void)(__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":1234 * * * for i in range(ndim): # <<<<<<<<<<<<<< * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 */ __pyx_t_3 = __pyx_v_ndim; __pyx_t_5 = __pyx_t_3; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1235 * * 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":1236 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< * * if slice_is_contig(src[0], order, ndim): */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; /* "View.MemoryView":1235 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ } } /* "View.MemoryView":1238 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1239 * * if slice_is_contig(src[0], order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); /* "View.MemoryView":1238 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ goto __pyx_L9; } /* "View.MemoryView":1241 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< * * return result */ /*else*/ { copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); } __pyx_L9:; /* "View.MemoryView":1243 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":1205 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1248 * * @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; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); /* "View.MemoryView":1251 * 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_ERR(2, 1251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; /* "View.MemoryView":1250 * 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_ERR(2, 1250, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1250, __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_ERR(2, 1250, __pyx_L1_error) /* "View.MemoryView":1248 * * @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 __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1254 * * @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; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1255 * @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_ERR(2, 1255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1255, __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_ERR(2, 1255, __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_UNPACK_METHODS && 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); } } __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __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_ERR(2, 1255, __pyx_L1_error) /* "View.MemoryView":1254 * * @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_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1258 * * @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; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1259 * @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 (unlikely(__pyx_t_1)) { /* "View.MemoryView":1260 * 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_ERR(2, 1260, __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_UNPACK_METHODS && 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); } } __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1260, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __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_ERR(2, 1260, __pyx_L1_error) /* "View.MemoryView":1259 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ } /* "View.MemoryView":1262 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_contents') */ /*else*/ { __Pyx_Raise(__pyx_v_error, 0, 0, 0); __PYX_ERR(2, 1262, __pyx_L1_error) } /* "View.MemoryView":1258 * * @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_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1265 * * @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; int __pyx_t_6; void *__pyx_t_7; int __pyx_t_8; /* "View.MemoryView":1273 * 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":1274 * """ * 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":1276 * 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":1277 * 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":1278 * 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":1281 * 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":1282 * * 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); /* "View.MemoryView":1281 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ goto __pyx_L3; } /* "View.MemoryView":1283 * 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":1284 * 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); /* "View.MemoryView":1283 * 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_L3:; /* "View.MemoryView":1286 * 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":1288 * 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; __pyx_t_3 = __pyx_t_5; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1289 * * 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":1290 * 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":1291 * 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":1292 * 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; /* "View.MemoryView":1290 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ goto __pyx_L7; } /* "View.MemoryView":1294 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ /*else*/ { __pyx_t_6 = __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_6 == ((int)-1))) __PYX_ERR(2, 1294, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":1289 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ } /* "View.MemoryView":1296 * _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":1297 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 1297, __pyx_L1_error) /* "View.MemoryView":1296 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ } } /* "View.MemoryView":1299 * _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":1301 * 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":1302 * * 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); /* "View.MemoryView":1301 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ } /* "View.MemoryView":1304 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(2, 1304, __pyx_L1_error) __pyx_v_tmpdata = __pyx_t_7; /* "View.MemoryView":1305 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< * * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; /* "View.MemoryView":1299 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(src, order, ndim): */ } /* "View.MemoryView":1307 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1310 * * * 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":1311 * * 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); /* "View.MemoryView":1310 * * * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): */ goto __pyx_L12; } /* "View.MemoryView":1312 * 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":1313 * 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); /* "View.MemoryView":1312 * 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_L12:; /* "View.MemoryView":1315 * 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":1317 * 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":1318 * * 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) */ (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); /* "View.MemoryView":1319 * 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":1320 * 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":1321 * 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; /* "View.MemoryView":1315 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ } /* "View.MemoryView":1307 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1323 * 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_8 = (__pyx_t_2 != 0); if (__pyx_t_8) { /* "View.MemoryView":1326 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(2, 1326, __pyx_L1_error) /* "View.MemoryView":1327 * * 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 == ((int)0))) __PYX_ERR(2, 1327, __pyx_L1_error) /* "View.MemoryView":1323 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1329 * 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":1330 * * 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":1331 * 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":1333 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1334 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_broadcast_leading') */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1265 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1337 * * @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; int __pyx_t_3; /* "View.MemoryView":1341 * 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":1343 * 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":1344 * * 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":1345 * 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":1346 * 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":1348 * 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; __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1349 * * 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":1350 * 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":1351 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1337 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ /* function exit code */ } /* "View.MemoryView":1359 * * @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":1363 * * * 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":1364 * * 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); /* "View.MemoryView":1363 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ } /* "View.MemoryView":1359 * * @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":1368 * * @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 = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); /* "View.MemoryView":1371 * 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":1368 * * @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 __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } /* "View.MemoryView":1374 * * @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; Py_ssize_t __pyx_t_3; int __pyx_t_4; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); /* "View.MemoryView":1378 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< * if ndim == 1: * if inc: */ __pyx_t_1 = (__pyx_v_shape[0]); __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1379 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_4) { /* "View.MemoryView":1380 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ __pyx_t_4 = (__pyx_v_inc != 0); if (__pyx_t_4) { /* "View.MemoryView":1381 * if ndim == 1: * if inc: * Py_INCREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * Py_DECREF((<PyObject **> data)[0]) */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); /* "View.MemoryView":1380 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ goto __pyx_L6; } /* "View.MemoryView":1383 * Py_INCREF((<PyObject **> data)[0]) * else: * Py_DECREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, */ /*else*/ { Py_DECREF((((PyObject **)__pyx_v_data)[0])); } __pyx_L6:; /* "View.MemoryView":1379 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ goto __pyx_L5; } /* "View.MemoryView":1385 * Py_DECREF((<PyObject **> data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * */ /*else*/ { /* "View.MemoryView":1386 * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, * ndim - 1, inc) # <<<<<<<<<<<<<< * * data += strides[0] */ __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":1388 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } /* "View.MemoryView":1374 * * @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":1394 * * @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":1397 * 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":1398 * 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":1400 * _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":1394 * * @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":1404 * * @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; Py_ssize_t __pyx_t_4; /* "View.MemoryView":1408 * 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":1409 * 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":1411 * 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":1412 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< * memcpy(data, item, itemsize) * data += stride */ __pyx_t_2 = __pyx_v_extent; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1413 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< * data += stride * else: */ (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); /* "View.MemoryView":1414 * 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); } /* "View.MemoryView":1411 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ goto __pyx_L3; } /* "View.MemoryView":1416 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) */ /*else*/ { __pyx_t_2 = __pyx_v_extent; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1417 * 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":1419 * _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":1404 * * @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 */ } /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v___pyx_type = 0; long __pyx_v___pyx_checksum; PyObject *__pyx_v___pyx_state = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,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); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(2, 1, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(2, 1, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(2, 1, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { 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); } __pyx_v___pyx_type = values[0]; __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(2, 1, __pyx_L3_error) __pyx_v___pyx_state = values[2]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 1, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_v___pyx_PickleError = 0; PyObject *__pyx_v___pyx_result = 0; PyObject *__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_t_6; __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); /* "(tree fragment)":4 * cdef object __pyx_PickleError * cdef object __pyx_result * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) */ __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); if (__pyx_t_1) { /* "(tree fragment)":5 * cdef object __pyx_result * if __pyx_checksum != 0xb068931: * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) */ __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_n_s_PickleError); __Pyx_GIVEREF(__pyx_n_s_PickleError); PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_2); __pyx_v___pyx_PickleError = __pyx_t_2; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":6 * if __pyx_checksum != 0xb068931: * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: */ __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_INCREF(__pyx_v___pyx_PickleError); __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(2, 6, __pyx_L1_error) /* "(tree fragment)":4 * cdef object __pyx_PickleError * cdef object __pyx_result * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) */ } /* "(tree fragment)":7 * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v___pyx_result = __pyx_t_3; __pyx_t_3 = 0; /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result */ __pyx_t_1 = (__pyx_v___pyx_state != Py_None); __pyx_t_6 = (__pyx_t_1 != 0); if (__pyx_t_6) { /* "(tree fragment)":9 * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) # <<<<<<<<<<<<<< * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): */ if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(2, 9, __pyx_L1_error) __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result */ } /* "(tree fragment)":10 * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result # <<<<<<<<<<<<<< * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v___pyx_result); __pyx_r = __pyx_v___pyx_result; goto __pyx_L0; /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_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.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v___pyx_PickleError); __Pyx_XDECREF(__pyx_v___pyx_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; Py_ssize_t __pyx_t_3; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); /* "(tree fragment)":12 * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): * __pyx_result.__dict__.update(__pyx_state[1]) */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(2, 12, __pyx_L1_error) } __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __Pyx_GOTREF(__pyx_v___pyx_result->name); __Pyx_DECREF(__pyx_v___pyx_result->name); __pyx_v___pyx_result->name = __pyx_t_1; __pyx_t_1 = 0; /* "(tree fragment)":13 * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< * __pyx_result.__dict__.update(__pyx_state[1]) */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(2, 13, __pyx_L1_error) } __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(2, 13, __pyx_L1_error) __pyx_t_4 = ((__pyx_t_3 > 1) != 0); if (__pyx_t_4) { } else { __pyx_t_2 = __pyx_t_4; goto __pyx_L4_bool_binop_done; } __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 13, __pyx_L1_error) __pyx_t_5 = (__pyx_t_4 != 0); __pyx_t_2 = __pyx_t_5; __pyx_L4_bool_binop_done:; if (__pyx_t_2) { /* "(tree fragment)":14 * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< */ __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(2, 14, __pyx_L1_error) } __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); if (likely(__pyx_t_8)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_8); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_7, function); } } __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":13 * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< * __pyx_result.__dict__.update(__pyx_state[1]) */ } /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /* 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_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static struct __pyx_vtabstruct_array __pyx_vtable_array; 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->__pyx_vtab = __pyx_vtabptr_array; 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)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_array(PyObject *o) { struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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 = __Pyx_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 __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); } static PyMethodDef __pyx_methods_array[] = { {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_array[] = { {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_array = { __pyx_array___len__, /*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 = { __pyx_array___len__, /*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) "GPy.util.choleskies_cython.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*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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[] = { {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_MemviewEnum = { PyVarObject_HEAD_INIT(0, 0) "GPy.util.choleskies_cython.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*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_memoryview(PyObject *o) { struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(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}, {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_memoryview[] = { {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)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) "GPy.util.choleskies_cython.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*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && 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_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_memoryviewslice = { PyVarObject_HEAD_INIT(0, 0) "GPy.util.choleskies_cython._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*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #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 #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec_choleskies_cython(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec_choleskies_cython}, {0, NULL} }; #endif static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "choleskies_cython", 0, /* m_doc */ #if CYTHON_PEP489_MULTI_PHASE_INIT 0, /* m_size */ #else -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif #ifndef CYTHON_SMALL_CODE #if defined(__clang__) #define CYTHON_SMALL_CODE #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define CYTHON_SMALL_CODE __attribute__((cold)) #else #define CYTHON_SMALL_CODE #endif #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 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_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 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_D, __pyx_k_D, sizeof(__pyx_k_D), 0, 0, 1, 1}, {&__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_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_n_s_GPy_util_choleskies_cython, __pyx_k_GPy_util_choleskies_cython, sizeof(__pyx_k_GPy_util_choleskies_cython), 0, 0, 1, 1}, {&__pyx_kp_s_GPy_util_choleskies_cython_pyx, __pyx_k_GPy_util_choleskies_cython_pyx, sizeof(__pyx_k_GPy_util_choleskies_cython_pyx), 0, 0, 1, 0}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 0, 0, 1, 0}, {&__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_L, __pyx_k_L, sizeof(__pyx_k_L), 0, 0, 1, 1}, {&__pyx_n_s_L_cont, __pyx_k_L_cont, sizeof(__pyx_k_L_cont), 0, 0, 1, 1}, {&__pyx_n_s_M, __pyx_k_M, sizeof(__pyx_k_M), 0, 0, 1, 1}, {&__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_n_s_N, __pyx_k_N, sizeof(__pyx_k_N), 0, 0, 1, 1}, {&__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_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, {&__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_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, {&__pyx_n_s_ascontiguousarray, __pyx_k_ascontiguousarray, sizeof(__pyx_k_ascontiguousarray), 0, 0, 1, 1}, {&__pyx_n_s_backprop_gradient, __pyx_k_backprop_gradient, sizeof(__pyx_k_backprop_gradient), 0, 0, 1, 1}, {&__pyx_n_s_backprop_gradient_par, __pyx_k_backprop_gradient_par, sizeof(__pyx_k_backprop_gradient_par), 0, 0, 1, 1}, {&__pyx_n_s_backprop_gradient_par_c, __pyx_k_backprop_gradient_par_c, sizeof(__pyx_k_backprop_gradient_par_c), 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_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 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_count, __pyx_k_count, sizeof(__pyx_k_count), 0, 0, 1, 1}, {&__pyx_n_s_d, __pyx_k_d, sizeof(__pyx_k_d), 0, 0, 1, 1}, {&__pyx_n_s_dL, __pyx_k_dL, sizeof(__pyx_k_dL), 0, 0, 1, 1}, {&__pyx_n_s_dL_dK, __pyx_k_dL_dK, sizeof(__pyx_k_dL_dK), 0, 0, 1, 1}, {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 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_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1}, {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 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_flat, __pyx_k_flat, sizeof(__pyx_k_flat), 0, 0, 1, 1}, {&__pyx_n_s_flat_to_triang, __pyx_k_flat_to_triang, sizeof(__pyx_k_flat_to_triang), 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_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 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_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_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, {&__pyx_n_s_m, __pyx_k_m, sizeof(__pyx_k_m), 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_mm, __pyx_k_mm, sizeof(__pyx_k_mm), 0, 0, 1, 1}, {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 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_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_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, {&__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_kp_s_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 0, 1, 0}, {&__pyx_kp_s_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 0, 1, 0}, {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 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_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 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_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, {&__pyx_n_s_ret, __pyx_k_ret, sizeof(__pyx_k_ret), 0, 0, 1, 1}, {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 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_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_triang_to_flat, __pyx_k_triang_to_flat, sizeof(__pyx_k_triang_to_flat), 0, 0, 1, 1}, {&__pyx_n_s_tril, __pyx_k_tril, sizeof(__pyx_k_tril), 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_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 27, __pyx_L1_error) #if PY_MAJOR_VERSION >= 3 __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) __PYX_ERR(0, 101, __pyx_L1_error) #else __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) __PYX_ERR(0, 101, __pyx_L1_error) #endif __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 272, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 856, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 1038, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(2, 148, __pyx_L1_error) __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(2, 151, __pyx_L1_error) __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(2, 2, __pyx_L1_error) __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(2, 400, __pyx_L1_error) __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(2, 609, __pyx_L1_error) __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(2, 828, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 272, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 276, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":306 * 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__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 306, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":856 * * 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__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 856, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":880 * 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__5 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 880, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1038 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 1038, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../../../.conda/envs/bays-dev-py2/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1044 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 1044, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "View.MemoryView":133 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(2, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "View.MemoryView":136 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(2, 136, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "View.MemoryView":148 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(2, 148, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); /* "View.MemoryView":176 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(2, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); /* "View.MemoryView":192 * 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__12 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(2, 192, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__12); __Pyx_GIVEREF(__pyx_tuple__12); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(2, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(2, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__14); __Pyx_GIVEREF(__pyx_tuple__14); /* "View.MemoryView":414 * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< * * have_slices, index = _unellipsify(index, self.view.ndim) */ __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(2, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); /* "View.MemoryView":491 * 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__16 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(2, 491, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); /* "View.MemoryView":516 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< * * if flags & PyBUF_ND: */ __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(2, 516, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__17); __Pyx_GIVEREF(__pyx_tuple__17); /* "View.MemoryView":566 * 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__18 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(2, 566, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__18); __Pyx_GIVEREF(__pyx_tuple__18); /* "View.MemoryView":573 * def suboffsets(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__19 = PyTuple_New(1); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(2, 573, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__19); __Pyx_INCREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); PyTuple_SET_ITEM(__pyx_tuple__19, 0, __pyx_int_neg_1); __Pyx_GIVEREF(__pyx_tuple__19); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(2, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__20); __Pyx_GIVEREF(__pyx_tuple__20); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(2, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__21); __Pyx_GIVEREF(__pyx_tuple__21); /* "View.MemoryView":678 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_slice__22 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__22)) __PYX_ERR(2, 678, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__22); __Pyx_GIVEREF(__pyx_slice__22); /* "View.MemoryView":699 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(2, 699, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__23); __Pyx_GIVEREF(__pyx_tuple__23); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(2, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__24); __Pyx_GIVEREF(__pyx_tuple__24); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(2, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__25); __Pyx_GIVEREF(__pyx_tuple__25); /* "GPy/util/choleskies_cython.pyx":14 * np.import_array() * * def flat_to_triang(double[:, :] flat, int M): # <<<<<<<<<<<<<< * """take a matrix N x D and return a D X M x M array where * */ __pyx_tuple__26 = PyTuple_Pack(9, __pyx_n_s_flat, __pyx_n_s_M, __pyx_n_s_D, __pyx_n_s_N, __pyx_n_s_count, __pyx_n_s_ret, __pyx_n_s_d, __pyx_n_s_m, __pyx_n_s_mm); if (unlikely(!__pyx_tuple__26)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__26); __Pyx_GIVEREF(__pyx_tuple__26); __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(2, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_GPy_util_choleskies_cython_pyx, __pyx_n_s_flat_to_triang, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(0, 14, __pyx_L1_error) /* "GPy/util/choleskies_cython.pyx":35 * return ret * * def triang_to_flat(double[:, :, :] L): # <<<<<<<<<<<<<< * cdef int D = L.shape[0] * cdef int M = L.shape[1] */ __pyx_tuple__28 = PyTuple_Pack(10, __pyx_n_s_L, __pyx_n_s_L, __pyx_n_s_D, __pyx_n_s_M, __pyx_n_s_N, __pyx_n_s_count, __pyx_n_s_flat, __pyx_n_s_d, __pyx_n_s_m, __pyx_n_s_mm); if (unlikely(!__pyx_tuple__28)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__28); __Pyx_GIVEREF(__pyx_tuple__28); __pyx_codeobj__29 = (PyObject*)__Pyx_PyCode_New(1, 0, 10, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_GPy_util_choleskies_cython_pyx, __pyx_n_s_triang_to_flat, 35, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__29)) __PYX_ERR(0, 35, __pyx_L1_error) /* "GPy/util/choleskies_cython.pyx":51 * return flat * * def backprop_gradient(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ __pyx_tuple__30 = PyTuple_Pack(7, __pyx_n_s_dL, __pyx_n_s_L, __pyx_n_s_dL_dK, __pyx_n_s_N, __pyx_n_s_k, __pyx_n_s_j, __pyx_n_s_i); if (unlikely(!__pyx_tuple__30)) __PYX_ERR(0, 51, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__30); __Pyx_GIVEREF(__pyx_tuple__30); __pyx_codeobj__31 = (PyObject*)__Pyx_PyCode_New(2, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__30, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_GPy_util_choleskies_cython_pyx, __pyx_n_s_backprop_gradient, 51, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__31)) __PYX_ERR(0, 51, __pyx_L1_error) /* "GPy/util/choleskies_cython.pyx":67 * return dL_dK * * def backprop_gradient_par(double[:,:] dL, double[:,:] L): # <<<<<<<<<<<<<< * cdef double[:,::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ __pyx_tuple__32 = PyTuple_Pack(7, __pyx_n_s_dL, __pyx_n_s_L, __pyx_n_s_dL_dK, __pyx_n_s_N, __pyx_n_s_k, __pyx_n_s_j, __pyx_n_s_i); if (unlikely(!__pyx_tuple__32)) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__32); __Pyx_GIVEREF(__pyx_tuple__32); __pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(2, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_GPy_util_choleskies_cython_pyx, __pyx_n_s_backprop_gradient_par, 67, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) __PYX_ERR(0, 67, __pyx_L1_error) /* "GPy/util/choleskies_cython.pyx":110 * dL[k, k] /= (2.0 * L[k, k]) * * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) */ __pyx_tuple__34 = PyTuple_Pack(5, __pyx_n_s_dL, __pyx_n_s_L, __pyx_n_s_dL_dK, __pyx_n_s_L_cont, __pyx_n_s_N); if (unlikely(!__pyx_tuple__34)) __PYX_ERR(0, 110, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__34); __Pyx_GIVEREF(__pyx_tuple__34); __pyx_codeobj__35 = (PyObject*)__Pyx_PyCode_New(2, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_GPy_util_choleskies_cython_pyx, __pyx_n_s_backprop_gradient_par_c, 110, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__35)) __PYX_ERR(0, 110, __pyx_L1_error) /* "View.MemoryView":286 * 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__36 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__36)) __PYX_ERR(2, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__36); __Pyx_GIVEREF(__pyx_tuple__36); /* "View.MemoryView":287 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__37)) __PYX_ERR(2, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__37); __Pyx_GIVEREF(__pyx_tuple__37); /* "View.MemoryView":288 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__38)) __PYX_ERR(2, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__38); __Pyx_GIVEREF(__pyx_tuple__38); /* "View.MemoryView":291 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__39)) __PYX_ERR(2, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__39); __Pyx_GIVEREF(__pyx_tuple__39); /* "View.MemoryView":292 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__40)) __PYX_ERR(2, 292, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__40); __Pyx_GIVEREF(__pyx_tuple__40); /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ __pyx_tuple__41 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__41)) __PYX_ERR(2, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__41); __Pyx_GIVEREF(__pyx_tuple__41); __pyx_codeobj__42 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__41, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__42)) __PYX_ERR(2, 1, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { /* InitThreads.init */ #ifdef WITH_THREAD PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ static int __Pyx_modinit_global_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); /*--- 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); __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); /*--- Variable export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); /*--- Function export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_type_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); /*--- Type init code ---*/ __pyx_vtabptr_array = &__pyx_vtable_array; __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(2, 105, __pyx_L1_error) __pyx_type___pyx_array.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(2, 105, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(2, 105, __pyx_L1_error) __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 279, __pyx_L1_error) __pyx_type___pyx_MemviewEnum.tp_print = 0; if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 279, __pyx_L1_error) __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_ERR(2, 330, __pyx_L1_error) __pyx_type___pyx_memoryview.tp_print = 0; if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(2, 330, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(2, 330, __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_ERR(2, 961, __pyx_L1_error) __pyx_type___pyx_memoryviewslice.tp_print = 0; if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(2, 961, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(2, 961, __pyx_L1_error) __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_type_import_code(void) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(3, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 206, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5numpy_dtype = __Pyx_ImportType(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(1, 206, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(1, 229, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(1, 233, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(1, 242, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(1, 918, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_variable_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); /*--- Variable import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_import_code(void) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); /*--- Function import code ---*/ __pyx_t_1 = PyImport_ImportModule("scipy.linalg.cython_blas"); if (!__pyx_t_1) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_ImportFunction(__pyx_t_1, "ddot", (void (**)(void))&__pyx_f_5scipy_6linalg_11cython_blas_ddot, "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_ImportFunction(__pyx_t_1, "dscal", (void (**)(void))&__pyx_f_5scipy_6linalg_11cython_blas_dscal, "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_ImportFunction(__pyx_t_1, "dsymv", (void (**)(void))&__pyx_f_5scipy_6linalg_11cython_blas_dsymv, "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_RefNannyFinishContext(); return -1; } #if PY_MAJOR_VERSION < 3 #ifdef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC void #else #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #endif #else #ifdef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC PyObject * #else #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #endif #endif #if PY_MAJOR_VERSION < 3 __Pyx_PyMODINIT_FUNC initcholeskies_cython(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC initcholeskies_cython(void) #else __Pyx_PyMODINIT_FUNC PyInit_choleskies_cython(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC PyInit_choleskies_cython(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { #if PY_VERSION_HEX >= 0x030700A1 static PY_INT64_T main_interpreter_id = -1; PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); if (main_interpreter_id == -1) { main_interpreter_id = current_id; return (unlikely(current_id == -1)) ? -1 : 0; } else if (unlikely(main_interpreter_id != current_id)) #else static PyInterpreterState *main_interpreter = NULL; PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; if (!main_interpreter) { main_interpreter = current_interpreter; } else if (unlikely(main_interpreter != current_interpreter)) #endif { PyErr_SetString( PyExc_ImportError, "Interpreter change detected - this module can only be loaded into one interpreter per process."); return -1; } return 0; } static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { if (allow_none || value != Py_None) { result = PyDict_SetItemString(moddict, to_name, value); } Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; if (__Pyx_check_single_interpreter()) return NULL; if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static CYTHON_SMALL_CODE int __pyx_pymod_exec_choleskies_cython(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; int __pyx_t_2; static PyThread_type_lock __pyx_t_3[8]; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m) { if (__pyx_m == __pyx_pyinit_module) return 0; PyErr_SetString(PyExc_RuntimeError, "Module 'choleskies_cython' has already been imported. Re-initialisation is not supported."); return -1; } #elif PY_MAJOR_VERSION >= 3 if (__pyx_m) return __Pyx_NewRef(__pyx_m); #endif #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("__Pyx_PyMODINIT_FUNC PyInit_choleskies_cython(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pxy_PyFrame_Initialize_Offsets __Pxy_PyFrame_Initialize_Offsets(); #endif __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __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 CYTHON_PEP489_MULTI_PHASE_INIT __pyx_m = __pyx_pyinit_module; Py_INCREF(__pyx_m); #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("choleskies_cython", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) #endif __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __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_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_GPy__util__choleskies_cython) { if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "GPy.util.choleskies_cython")) { if (unlikely(PyDict_SetItemString(modules, "GPy.util.choleskies_cython", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(); (void)__Pyx_modinit_variable_export_code(); (void)__Pyx_modinit_function_export_code(); if (unlikely(__Pyx_modinit_type_init_code() != 0)) goto __pyx_L1_error; if (unlikely(__Pyx_modinit_type_import_code() != 0)) goto __pyx_L1_error; (void)__Pyx_modinit_variable_import_code(); if (unlikely(__Pyx_modinit_function_import_code() != 0)) goto __pyx_L1_error; /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "GPy/util/choleskies_cython.pyx":7 * # Copyright James Hensman and Alan Saul 2015 * * import numpy as np # <<<<<<<<<<<<<< * from cython.parallel import prange, parallel * cimport numpy as np */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 7, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "GPy/util/choleskies_cython.pyx":12 * cimport scipy.linalg.cython_blas as cblas * * np.import_array() # <<<<<<<<<<<<<< * * def flat_to_triang(double[:, :] flat, int M): */ __pyx_t_2 = __pyx_f_5numpy_import_array(); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 12, __pyx_L1_error) /* "GPy/util/choleskies_cython.pyx":14 * np.import_array() * * def flat_to_triang(double[:, :] flat, int M): # <<<<<<<<<<<<<< * """take a matrix N x D and return a D X M x M array where * */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_3GPy_4util_17choleskies_cython_1flat_to_triang, NULL, __pyx_n_s_GPy_util_choleskies_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_flat_to_triang, __pyx_t_1) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "GPy/util/choleskies_cython.pyx":35 * return ret * * def triang_to_flat(double[:, :, :] L): # <<<<<<<<<<<<<< * cdef int D = L.shape[0] * cdef int M = L.shape[1] */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_3GPy_4util_17choleskies_cython_3triang_to_flat, NULL, __pyx_n_s_GPy_util_choleskies_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_triang_to_flat, __pyx_t_1) < 0) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "GPy/util/choleskies_cython.pyx":51 * return flat * * def backprop_gradient(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_3GPy_4util_17choleskies_cython_5backprop_gradient, NULL, __pyx_n_s_GPy_util_choleskies_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 51, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_backprop_gradient, __pyx_t_1) < 0) __PYX_ERR(0, 51, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "GPy/util/choleskies_cython.pyx":67 * return dL_dK * * def backprop_gradient_par(double[:,:] dL, double[:,:] L): # <<<<<<<<<<<<<< * cdef double[:,::1] dL_dK = np.tril(dL) * cdef int N = L.shape[0] */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_3GPy_4util_17choleskies_cython_7backprop_gradient_par, NULL, __pyx_n_s_GPy_util_choleskies_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_backprop_gradient_par, __pyx_t_1) < 0) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "GPy/util/choleskies_cython.pyx":110 * dL[k, k] /= (2.0 * L[k, k]) * * def backprop_gradient_par_c(double[:, :] dL, double[:, :] L): # <<<<<<<<<<<<<< * cdef double[:, ::1] dL_dK = np.tril(dL) # makes a copy, c-contig * cdef double[:, ::1] L_cont = np.ascontiguousarray(L) */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_3GPy_4util_17choleskies_cython_9backprop_gradient_par_c, NULL, __pyx_n_s_GPy_util_choleskies_cython); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 110, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_backprop_gradient_par_c, __pyx_t_1) < 0) __PYX_ERR(0, 110, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "GPy/util/choleskies_cython.pyx":1 * #cython: wraparaound=False # <<<<<<<<<<<<<< * #cython: boundscheck=False * #cython: nonecheck=False */ __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":209 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * def __dealloc__(array self): */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 209, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(2, 209, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_array_type); /* "View.MemoryView":286 * 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_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(generic); __Pyx_DECREF_SET(generic, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":287 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(strided); __Pyx_DECREF_SET(strided, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":288 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect); __Pyx_DECREF_SET(indirect, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":291 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(contiguous); __Pyx_DECREF_SET(contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":292 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 292, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect_contiguous); __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":316 * * DEF THREAD_LOCKS_PREALLOCATED = 8 * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ * PyThread_allocate_lock(), */ __pyx_memoryview_thread_locks_used = 0; /* "View.MemoryView":317 * DEF THREAD_LOCKS_PREALLOCATED = 8 * cdef int __pyx_memoryview_thread_locks_used = 0 * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< * PyThread_allocate_lock(), * PyThread_allocate_lock(), */ __pyx_t_3[0] = PyThread_allocate_lock(); __pyx_t_3[1] = PyThread_allocate_lock(); __pyx_t_3[2] = PyThread_allocate_lock(); __pyx_t_3[3] = PyThread_allocate_lock(); __pyx_t_3[4] = PyThread_allocate_lock(); __pyx_t_3[5] = PyThread_allocate_lock(); __pyx_t_3[6] = PyThread_allocate_lock(); __pyx_t_3[7] = PyThread_allocate_lock(); memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_3, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); /* "View.MemoryView":545 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 545, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(2, 545, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryview_type); /* "View.MemoryView":991 * return self.from_object * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 991, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(2, 991, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryviewslice_type); /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(2, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init GPy.util.choleskies_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init GPy.util.choleskies_cython"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #elif PY_MAJOR_VERSION >= 3 return __pyx_m; #else return; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule(modname); if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* PyObjectGetAttrStr */ #if CYTHON_USE_TYPE_SLOTS 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); } #endif /* GetBuiltinName */ 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; } /* RaiseArgTupleInvalid */ 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); } /* RaiseDoubleKeywords */ 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 } /* ParseKeywords */ 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; } /* GetModuleGlobalName */ #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } else if (unlikely(PyErr_Occurred())) { return NULL; } #else result = PyDict_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } #endif #else result = PyObject_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); } /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); int flags = PyCFunction_GET_FLAGS(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif #endif /* PyObjectCall */ #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 /* PyObjectCall2Args */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { PyObject *args, *result = NULL; #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyFunction_FastCall(function, args, 2); } #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyCFunction_FastCall(function, args, 2); } #endif args = PyTuple_New(2); if (unlikely(!args)) goto done; Py_INCREF(arg1); PyTuple_SET_ITEM(args, 0, arg1); Py_INCREF(arg2); PyTuple_SET_ITEM(args, 1, arg2); Py_INCREF(function); result = __Pyx_PyObject_Call(function, args, NULL); Py_DECREF(args); Py_DECREF(function); done: return result; } /* PyObjectCallMethO */ #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 /* PyObjectCallOneArg */ #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) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif if (likely(PyCFunction_Check(func))) { if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* MemviewSliceInit */ 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; } #ifndef Py_NO_RETURN #define Py_NO_RETURN #endif static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { va_list vargs; char msg[200]; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, fmt); #else va_start(vargs); #endif vsnprintf(msg, 200, fmt, vargs); va_end(vargs); Py_FatalError(msg); } 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; } } /* None */ 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; } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; 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); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* WriteUnraisableException */ static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback, CYTHON_UNUSED int nogil) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_PyThreadState_declare #ifdef WITH_THREAD PyGILState_STATE state; if (nogil) state = PyGILState_Ensure(); #ifdef _MSC_VER else state = (PyGILState_STATE)-1; #endif #endif __Pyx_PyThreadState_assign __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); } #ifdef WITH_THREAD if (nogil) PyGILState_Release(state); #endif } /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare 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_PyThreadState_assign __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) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } 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 (cause) { 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 = __Pyx_PyThreadState_Current; 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 /* DictGetItem */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { if (unlikely(PyTuple_Check(key))) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) { PyErr_SetObject(PyExc_KeyError, args); Py_DECREF(args); } } else { PyErr_SetObject(PyExc_KeyError, key); } } return NULL; } Py_INCREF(value); return value; } #endif /* RaiseTooManyValuesToUnpack */ 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); } /* RaiseNeedMoreValuesToUnpack */ 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"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(__Pyx_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* GetTopmostException */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) { _PyErr_StackItem *exc_info = tstate->exc_info; while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && exc_info->previous_item != NULL) { exc_info = exc_info->previous_item; } return exc_info; } #endif /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); *type = exc_info->exc_type; *value = exc_info->exc_value; *tb = exc_info->exc_traceback; #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; #endif Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = type; exc_info->exc_value = value; exc_info->exc_traceback = tb; #else 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; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1; } return 0; } static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; if (unlikely(PyTuple_Check(err))) return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; 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_FAST_THREAD_STATE 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_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = local_type; exc_info->exc_value = local_value; exc_info->exc_traceback = local_tb; } #else 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; #endif 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; } /* ArgTypeTest */ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } else if (exact) { #if PY_MAJOR_VERSION == 2 if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(__Pyx_TypeCheck(obj, type))) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } /* BytesEquals */ 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; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t hash1, hash2; hash1 = ((PyBytesObject*)s1)->ob_shash; hash2 = ((PyBytesObject*)s2)->ob_shash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { return (equals == Py_NE); } #endif 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 } /* UnicodeEquals */ 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; } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; #if CYTHON_PEP393_ENABLED hash1 = ((PyASCIIObject*)s1)->hash; hash2 = ((PyASCIIObject*)s2)->hash; #else hash1 = ((PyUnicodeObject*)s1)->hash; hash2 = ((PyUnicodeObject*)s2)->hash; #endif if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { goto return_ne; } } #endif 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_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif 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 } /* None */ 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; } /* GetAttr */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_USE_TYPE_SLOTS #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); } /* GetItemInt */ static 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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, wrapped_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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, wrapped_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, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(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(__Pyx_is_valid_index(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)) return NULL; PyErr_Clear(); } } 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)); } /* ObjectGetItem */ #if CYTHON_USE_TYPE_SLOTS static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { PyObject *runerr; Py_ssize_t key_value; PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; if (unlikely(!(m && m->sq_item))) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); return NULL; } key_value = __Pyx_PyIndex_AsSsize_t(index); if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); } if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { PyErr_Clear(); PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); } return NULL; } static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; if (likely(m && m->mp_subscript)) { return m->mp_subscript(obj, key); } return __Pyx_PyObject_GetIndex(obj, key); } #endif /* decode_c_string */ 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))) { size_t slen = strlen(cstring); if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { PyErr_SetString(PyExc_OverflowError, "c-string too long to convert to Python"); return NULL; } length = (Py_ssize_t) slen; 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); } } /* GetAttr3 */ static PyObject *__Pyx_GetAttr3Default(PyObject *d) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) return NULL; __Pyx_PyErr_Clear(); Py_INCREF(d); return d; } static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { PyObject *r = __Pyx_GetAttr(o, n); return (likely(r)) ? r : __Pyx_GetAttr3Default(d); } /* SwapException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = *type; exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else 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; #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #endif /* Import */ 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_MAJOR_VERSION < 3 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, '.')) { module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_MAJOR_VERSION < 3 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_MAJOR_VERSION < 3 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } #if PY_MAJOR_VERSION == 2 static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { PyObject *exception, *value, *tb; int res; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&exception, &value, &tb); res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } if (!res) { res = PyObject_IsSubclass(err, exc_type2); if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } } __Pyx_ErrRestore(exception, value, tb); return res; } #else static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; if (!res) { res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } return res; } #endif static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; assert(PyExceptionClass_Check(exc_type)); n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { PyObject *t = PyTuple_GET_ITEM(tuple, i); #if PY_MAJOR_VERSION < 3 if (likely(exc_type == t)) return 1; #endif if (likely(PyExceptionClass_Check(t))) { if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1; } else { } } return 0; } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { if (likely(err == exc_type)) return 1; if (likely(PyExceptionClass_Check(err))) { if (likely(PyExceptionClass_Check(exc_type))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); } else if (likely(PyTuple_Check(exc_type))) { return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type); } else { } } return PyErr_GivenExceptionMatches(err, exc_type); } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { assert(PyExceptionClass_Check(exc_type1)); assert(PyExceptionClass_Check(exc_type2)); if (likely(err == exc_type1 || err == exc_type2)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); } return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); } #endif /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a + b); if (likely((x^a) >= 0 || (x^b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_add(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } } x = a + b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla + llb; return PyLong_FromLongLong(llx); #endif } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("add", return NULL) result = ((double)a) + (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } #endif /* None */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* HasAttr */ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { PyObject *r; if (unlikely(!__Pyx_PyBaseString_Check(n))) { PyErr_SetString(PyExc_TypeError, "hasattr(): attribute name must be string"); return -1; } r = __Pyx_GetAttr(o, n); if (unlikely(!r)) { PyErr_Clear(); return 0; } else { Py_DECREF(r); return 1; } } /* PyObject_GenericGetAttrNoDict */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, attr_name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(attr_name)); #endif return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { PyObject *descr; PyTypeObject *tp = Py_TYPE(obj); if (unlikely(!PyString_Check(attr_name))) { return PyObject_GenericGetAttr(obj, attr_name); } assert(!tp->tp_dictoffset); descr = _PyType_Lookup(tp, attr_name); if (unlikely(!descr)) { return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); } Py_INCREF(descr); #if PY_MAJOR_VERSION < 3 if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) #endif { descrgetfunc f = Py_TYPE(descr)->tp_descr_get; if (unlikely(f)) { PyObject *res = f(descr, obj, (PyObject *)tp); Py_DECREF(descr); return res; } } return descr; } #endif /* PyObject_GenericGetAttr */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { return PyObject_GenericGetAttr(obj, attr_name); } return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); } #endif /* SetVTable */ 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; } /* SetupReduce */ static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { int ret; PyObject *name_attr; name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); if (likely(name_attr)) { ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); } else { ret = -1; } if (unlikely(ret < 0)) { PyErr_Clear(); ret = 0; } Py_XDECREF(name_attr); return ret; } static int __Pyx_setup_reduce(PyObject* type_obj) { int ret = 0; PyObject *object_reduce = NULL; PyObject *object_reduce_ex = NULL; PyObject *reduce = NULL; PyObject *reduce_ex = NULL; PyObject *reduce_cython = NULL; PyObject *setstate = NULL; PyObject *setstate_cython = NULL; #if CYTHON_USE_PYTYPE_LOOKUP if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto GOOD; #else if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto GOOD; #endif #if CYTHON_USE_PYTYPE_LOOKUP object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; #else object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; #endif reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto BAD; if (reduce_ex == object_reduce_ex) { #if CYTHON_USE_PYTYPE_LOOKUP object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto BAD; #else object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto BAD; #endif reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto BAD; if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { reduce_cython = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_cython); if (unlikely(!reduce_cython)) goto BAD; ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto BAD; setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); if (!setstate) PyErr_Clear(); if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { setstate_cython = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate_cython); if (unlikely(!setstate_cython)) goto BAD; ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto BAD; } PyType_Modified((PyTypeObject*)type_obj); } } goto GOOD; BAD: if (!PyErr_Occurred()) PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); ret = -1; GOOD: #if !CYTHON_USE_PYTYPE_LOOKUP Py_XDECREF(object_reduce); Py_XDECREF(object_reduce_ex); #endif Py_XDECREF(reduce); Py_XDECREF(reduce_ex); Py_XDECREF(reduce_cython); Py_XDECREF(setstate); Py_XDECREF(setstate_cython); return ret; } /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size) { PyObject *result = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif result = PyObject_GetAttrString(module, class_name); 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 ((size_t)basicsize < size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(result); return NULL; } #endif /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif if (unlikely(!__pyx_cython_runtime)) { return c_line; } __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); if (likely(cython_runtime_dict)) { __PYX_PY_DICT_LOOKUP_IF_MODIFIED( use_cline, *cython_runtime_dict, __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ 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 - start) / 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); } /* AddTraceback */ #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; PyThreadState *tstate = __Pyx_PyThreadState_Current; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } 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( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #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 (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); if (__Pyx_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 ((0)) {} else if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); view->obj = NULL; Py_DECREF(obj); } #endif /* MemviewSliceIsContig */ 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; } /* OverlappingSlices */ 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); } /* Capsule */ 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; } /* IsLittleEndian */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) { union { uint32_t u32; uint8_t u8[4]; } S; S.u32 = 0x01020304; return S.u8[0] == 4; } /* BufferFormatCheck */ 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 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_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_Is_Little_Endian()) { 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; } CYTHON_FALLTHROUGH; 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; } CYTHON_FALLTHROUGH; 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; } } } } /* TypeInfoCompare */ 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; } /* MemviewSliceValidateAndInit */ 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; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__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_RO | writable_flag, 2, &__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; } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ 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 (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsdsds_double(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__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_RO | writable_flag, 3, &__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; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 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); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 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); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* MemviewDtypeToObject */ static CYTHON_INLINE PyObject *__pyx_memview_get_double(const char *itemp) { return (PyObject *) PyFloat_FromDouble(*(double *) itemp); } static CYTHON_INLINE int __pyx_memview_set_double(const char *itemp, PyObject *obj) { double value = __pyx_PyFloat_AsDouble(obj); if ((value == (double)-1) && PyErr_Occurred()) return 0; *(double *) itemp = value; return 1; } /* Declarations */ #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 /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_float(__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_sum_float(__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_diff_float(__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_prod_float(__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; } #if 1 static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabsf(b.real) >= fabsf(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { float r = b.imag / b.real; float s = 1.0 / (b.real + b.imag * r); return __pyx_t_float_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { float r = b.real / b.imag; float s = 1.0 / (b.imag + b.real * r); return __pyx_t_float_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else { float denom = b.real * b.real + b.imag * b.imag; return __pyx_t_float_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__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_zero_float(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__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_abs_float(__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_pow_float(__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_prod_float(a, a); return __Pyx_c_prod_float(a, a); case 3: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, a); case 4: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = powf(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2f(0, -1); } } else { r = __Pyx_c_abs_float(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 /* Declarations */ #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 /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_double(__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_double(__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_double(__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_double(__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; } #if 1 static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabs(b.real) >= fabs(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { double r = b.imag / b.real; double s = 1.0 / (b.real + b.imag * r); return __pyx_t_double_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { double r = b.real / b.imag; double s = 1.0 / (b.imag + b.real * r); return __pyx_t_double_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else { double denom = b.real * b.real + b.imag * b.imag; return __pyx_t_double_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__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_double(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__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_double(__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_double(__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_double(a, a); return __Pyx_c_prod_double(a, a); case 3: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, a); case 4: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = pow(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2(0, -1); } } else { r = __Pyx_c_abs_double(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 /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { const enum NPY_TYPES neg_one = (enum NPY_TYPES) ((enum NPY_TYPES) 0 - (enum NPY_TYPES) 1), const_zero = (enum NPY_TYPES) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(enum NPY_TYPES) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(enum NPY_TYPES) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), little, !is_unsigned); } } /* MemviewSliceCopyTemplate */ 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; } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 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_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #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_IntOrLong(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_IntOrLong(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; } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 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_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #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_IntOrLong(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_IntOrLong(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; } /* CIntFromPy */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { const char neg_one = (char) ((char) 0 - (char) 1), const_zero = (char) 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_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (char) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(char) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) case -2: if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -3: if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -4: if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; } #endif if (sizeof(char) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #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_IntOrLong(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_IntOrLong(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; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_double(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, &__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; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 2, &__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; } /* CheckBinaryVersion */ 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; } /* FunctionImport */ #ifndef __PYX_HAVE_RT_ImportFunction #define __PYX_HAVE_RT_ImportFunction static int __Pyx_ImportFunction(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { PyObject *d = 0; PyObject *cobj = 0; union { void (*fp)(void); void *p; } tmp; d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); if (!d) goto bad; cobj = PyDict_GetItemString(d, funcname); if (!cobj) { PyErr_Format(PyExc_ImportError, "%.200s does not export expected C function %.200s", PyModule_GetName(module), funcname); goto bad; } #if PY_VERSION_HEX >= 0x02070000 if (!PyCapsule_IsValid(cobj, sig)) { PyErr_Format(PyExc_TypeError, "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); goto bad; } tmp.p = PyCapsule_GetPointer(cobj, sig); #else {const char *desc, *s1, *s2; desc = (const char *)PyCObject_GetDesc(cobj); if (!desc) goto bad; s1 = desc; s2 = sig; while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } if (*s1 != *s2) { PyErr_Format(PyExc_TypeError, "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", PyModule_GetName(module), funcname, sig, desc); goto bad; } tmp.p = PyCObject_AsVoidPtr(cobj);} #endif *f = tmp.fp; if (!(*f)) goto bad; Py_DECREF(d); return 0; bad: Py_XDECREF(d); return -1; } #endif /* InitStrings */ 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; if (PyObject_Hash(*t->p) == -1) 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 const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { 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 static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(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 #endif static CYTHON_INLINE const 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)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) 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 int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; retval = __Pyx_PyObject_IsTrue(x); Py_DECREF(x); return retval; } static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", Py_TYPE(result)->tp_name)) { Py_DECREF(result); return NULL; } return result; } #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", type_name, type_name, Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) #else if (likely(PyLong_Check(x))) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; res = m->nb_long(x); } #else if (likely(m && m->nb_int)) { name = "int"; res = m->nb_int(x); } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } #endif if (likely(res)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else if (unlikely(!PyLong_CheckExact(res))) { #endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } 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))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #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_PyBool_FromLong(long b) { return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
minibatch_kmeans.c
#include "kmeans.h" #include "kmeans_utils.h" #include "minibatch_commons.h" #include "../../utils/matrix/csr_matrix/csr_to_vector_list.h" #include "../../utils/matrix/vector_list/vector_list_math.h" #include "../../utils/matrix/csr_matrix/csr_math.h" #include "../../utils/vector/common/common_vector_math.h" #include "../../utils/vector/sparse/sparse_vector_math.h" #include "../../utils/fcl_logging.h" #include <unistd.h> #include <float.h> #include <math.h> struct kmeans_result* bv_minibatch_kmeans(struct csr_matrix* samples , struct kmeans_params *prms) { uint32_t i; uint64_t j; uint64_t block_vectors_dim; /* size of block vectors */ uint64_t samples_per_batch; uint64_t keys_per_block; uint32_t max_not_improved_counter; uint32_t disable_optimizations; VALUE_TYPE desired_bv_annz; /* desired size of the block vectors */ uint32_t* chosen_sample_map; struct convergence_context conv_ctx; struct sparse_vector* block_vectors_clusters; /* block vector matrix of clusters */ struct kmeans_result* res; struct general_kmeans_context ctx; disable_optimizations = prms->kmeans_algorithm_id == ALGORITHM_MINIBATCH_KMEANS; initialize_general_context(prms, &ctx, samples); conv_ctx.initialized = 0; max_not_improved_counter = 20; /* if clusters_raw was filled (this happens in kmeans++) free it * since minibatch k-means uses a different strategy to fill the raw clusters */ free_cluster_hashmaps(ctx.clusters_raw, ctx.no_clusters); /* reset cluster counts since minibatch kmeans handels them differently */ for (i = 0; i < ctx.no_clusters; i++) ctx.cluster_counts[i] = 0; desired_bv_annz = d_get_subfloat_default(&(prms->tr) , "additional_params", "bv_annz", 0.3); block_vectors_dim = 0; keys_per_block = 0; chosen_sample_map = NULL; /* samples_per_batch = ctx.samples->sample_count; */ samples_per_batch = d_get_subint_default(&(prms->tr) , "additional_params", "samples_per_batch", ctx.samples->sample_count * 0.05); if (!disable_optimizations) { /* search for a suitable size of the block vectors for the input samples and create them */ block_vectors_dim = search_block_vector_size(ctx.samples, desired_bv_annz, prms->verbose); keys_per_block = ctx.samples->dim / block_vectors_dim; if (ctx.samples->dim % block_vectors_dim > 0) keys_per_block++; /* create block vectors for the clusters */ create_block_vectors_list_from_vector_list(ctx.cluster_vectors , block_vectors_dim , ctx.no_clusters , ctx.samples->dim , &block_vectors_clusters); } create_chosen_sample_map(&chosen_sample_map, ctx.samples->sample_count, samples_per_batch, &(prms->seed)); for (i = 0; i < prms->iteration_limit && !ctx.converged && !prms->stop; i++) { /* track how many blockvector calculations were made / saved */ uint64_t saved_calculations_bv, saved_calculations_prev_cluster; uint64_t done_blockvector_calcs, saved_calculations_cauchy; /* reset all calculation counters */ done_blockvector_calcs = 0; saved_calculations_cauchy = 0; saved_calculations_prev_cluster = 0; saved_calculations_bv = 0; /* initialize data needed for the iteration */ pre_process_iteration(&ctx); #pragma omp parallel for schedule(dynamic, 1000) for (j = 0; j < ctx.samples->sample_count; j++) { /* iterate over all samples */ VALUE_TYPE dist; uint64_t cluster_id, sample_id; struct sparse_vector bv; bv.nnz = 0; bv.keys = NULL; bv.values = NULL; if (!prms->stop && chosen_sample_map[j]) { sample_id = j; if (omp_get_thread_num() == 0) check_signals(&(prms->stop)); for (cluster_id = 0; cluster_id < ctx.no_clusters; cluster_id++) { /* iterate over all cluster centers */ if (!disable_optimizations) { /* bv_minibatch_kmeans */ /* we already know the distance to the cluster from last iteration */ if (cluster_id == ctx.previous_cluster_assignments[sample_id]) continue; /* evaluate cauchy approximation. fast but not good */ dist = lower_bound_euclid(ctx.vector_lengths_clusters[cluster_id] , ctx.vector_lengths_samples[sample_id]); if (dist >= ctx.cluster_distances[sample_id]) { /* approximated distance is larger than current best distance. skip full distance calculation */ saved_calculations_cauchy += 1; goto end; } if (bv.keys == NULL) { create_block_vector_from_csr_matrix_vector(ctx.samples , sample_id , keys_per_block , &bv); } /* evaluate block vector approximation. */ dist = euclid_vector(bv.keys, bv.values, bv.nnz , block_vectors_clusters[cluster_id].keys , block_vectors_clusters[cluster_id].values , block_vectors_clusters[cluster_id].nnz , ctx.vector_lengths_samples[sample_id] , ctx.vector_lengths_clusters[cluster_id]); done_blockvector_calcs += 1; if (dist >= ctx.cluster_distances[sample_id] && fabs(dist - ctx.cluster_distances[sample_id]) >= 1e-6) { /* approximated distance is larger than current best distance. skip full distance calculation */ saved_calculations_bv += 1; goto end; } } /* if we reached this point we need to calculate a full euclidean distance */ dist = euclid_vector_list(ctx.samples, sample_id, ctx.cluster_vectors, cluster_id , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); ctx.done_calculations += 1; if (dist < ctx.cluster_distances[sample_id]) { /* replace current best distance with new distance */ ctx.cluster_distances[sample_id] = dist; ctx.cluster_assignments[sample_id] = cluster_id; } end:; } } if (!disable_optimizations) { free_null(bv.keys); free_null(bv.values); } } check_signals(&(prms->stop)); post_process_iteration_minibatch(&ctx , chosen_sample_map , max_not_improved_counter , &conv_ctx); /* shift clusters to new position */ calculate_shifted_clusters_minibatch_kmeans(&ctx, chosen_sample_map); /* calculate_shifted_clusters(&ctx); */ switch_to_shifted_clusters(&ctx); create_chosen_sample_map(&chosen_sample_map, ctx.samples->sample_count, samples_per_batch, &(prms->seed)); if (!disable_optimizations) { /* update only block vectors for cluster that shifted */ update_changed_blockvectors(ctx.cluster_vectors , block_vectors_dim , ctx.no_clusters , ctx.samples->dim , ctx.clusters_not_changed , block_vectors_clusters); d_add_ilist(&(prms->tr), "iteration_bv_calcs", done_blockvector_calcs); d_add_ilist(&(prms->tr), "iteration_bv_calcs_success", saved_calculations_bv + saved_calculations_cauchy); } #pragma omp parallel for for (j = 0; j < ctx.samples->sample_count; j++) { /* iterate over all chosen samples for the next iteration and * update their distance to their current cluster */ if (chosen_sample_map[j]) { ctx.cluster_distances[j] = euclid_vector_list(ctx.samples, j , ctx.cluster_vectors, ctx.cluster_assignments[j] , ctx.vector_lengths_samples , ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; ctx.total_no_calcs += 1; } } print_iteration_summary(&ctx, prms, i); /* print block vector statistics */ if (prms->verbose) LOG_INFO("BV statistics c:%" PRINTF_INT64_MODIFIER "u/b:%" PRINTF_INT64_MODIFIER "u/db:%" PRINTF_INT64_MODIFIER "u/pc:%" PRINTF_INT64_MODIFIER "u" , saved_calculations_cauchy , saved_calculations_bv , done_blockvector_calcs , saved_calculations_prev_cluster); } if (prms->verbose) LOG_INFO("total total_no_calcs = %" PRINTF_INT64_MODIFIER "u", ctx.total_no_calcs); res = create_kmeans_result(prms, &ctx); /* cleanup all */ if (!disable_optimizations) { free_vector_list(block_vectors_clusters, ctx.no_clusters); free(block_vectors_clusters); } free_null(chosen_sample_map); free_general_context(&ctx, prms); return res; }
Graph.h
/* * Graph.h * * Created on: 01.06.2014 * Author: Christian Staudt (christian.staudt@kit.edu), Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com) */ #ifndef GRAPH_H_ #define GRAPH_H_ #include <algorithm> #include <vector> #include <stack> #include <queue> #include <utility> #include <stdexcept> #include <functional> #include <unordered_set> #include "../Globals.h" #include "Coordinates.h" #include "../viz/Point.h" #include "../auxiliary/Random.h" #include "../auxiliary/FunctionTraits.h" #include "../auxiliary/Log.h" namespace NetworKit { /** * A weighted edge used for the graph constructor with * initializer list syntax. */ struct WeightedEdge { node u, v; edgeweight weight; WeightedEdge(node u, node v, edgeweight w) : u(u), v(v), weight(w) { } }; inline bool operator<(const WeightedEdge& e1, const WeightedEdge& e2) { return e1.weight < e2.weight; } struct Edge { node u, v; Edge(node _u, node _v, bool sorted = false) { if (sorted) { u = std::min(_u, _v); v = std::max(_u, _v); } else { u = _u; v = _v; } } }; inline bool operator==(const Edge& e1, const Edge& e2) { return e1.u == e2.u && e1.v == e2.v; } } namespace std { template<> struct hash<NetworKit::Edge> { size_t operator()(const NetworKit::Edge& e) const { return hash_node(e.u) ^ hash_node(e.v); } hash<NetworKit::node> hash_node; }; } namespace NetworKit { // forward declaration to randomization/CurveballImpl.h namespace CurveballDetails {class CurveballMaterialization;} /** * @ingroup graph * A graph (with optional weights) and parallel iterator methods. */ class Graph final { friend class ParallelPartitionCoarsening; friend class GraphBuilder; friend class CurveballDetails::CurveballMaterialization; private: // graph attributes count id; //!< unique graph id, starts at 0 std::string name; //!< name of the graph, initially G#ID // scalars count n; //!< current number of nodes count m; //!< current number of edges count storedNumberOfSelfLoops; //!< current number of self loops, edges which have the same origin and target node z; //!< current upper bound of node ids, z will be the id of the next node edgeid omega; //!< current upper bound of edge ids, will be the id of the next edge count t; //!< current time step bool weighted; //!< true if the graph is weighted, false otherwise bool directed; //!< true if the graph is directed, false otherwise bool edgesIndexed; //!< true if edge ids have been assigned // per node data std::vector<bool> exists; //!< exists[v] is true if node v has not been removed from the graph Coordinates<float> coordinates; //!< coordinates of nodes (if present) std::vector<count> inDeg; //!< only used for directed graphs, number of edges incoming per node std::vector<count> outDeg; //!< degree of every node, zero if node was removed. For directed graphs only outgoing edges count std::vector< std::vector<node> > inEdges; //!< only used for directed graphs, inEdges[v] contains all nodes u that have an edge (u, v) std::vector< std::vector<node> > outEdges; //!< (outgoing) edges, for each edge (u, v) v is saved in outEdges[u] and for undirected also u in outEdges[v] std::vector< std::vector<edgeweight> > inEdgeWeights; //!< only used for directed graphs, same schema as inEdges std::vector< std::vector<edgeweight> > outEdgeWeights; //!< same schema (and same order!) as outEdges std::vector< std::vector<edgeid> > inEdgeIds; //!< only used for directed graphs, same schema as inEdges std::vector< std::vector<edgeid> > outEdgeIds; //!< same schema (and same order!) as outEdges /** * Returns the next unique graph id. */ count getNextGraphId(); /** * Returns the index of node u in the array of incoming edges of node v. (for directed graphs inEdges is searched, while for indirected outEdges is searched, which gives the same result as indexInOutEdgeArray). */ index indexInInEdgeArray(node v, node u) const; /** * Returns the index of node v in the array of outgoing edges of node u. */ index indexInOutEdgeArray(node u, node v) const; /** * Returns the edge weight of the outgoing edge of index i in the outgoing edges of node u * @param u The node * @param i The index * @return The weight of the outgoing edge or defaultEdgeWeight if the graph is unweighted */ template<bool hasWeights> inline edgeweight getOutEdgeWeight(node u, index i) const; /** * Returns the edge weight of the incoming edge of index i in the incoming edges of node u * * @param u The node * @param i The index in the incoming edge array * @return The weight of the incoming edge */ template<bool hasWeights> inline edgeweight getInEdgeWeight(node u, index i) const; /** * Returns the edge id of the edge of index i in the outgoing edges of node u * * @param u The node * @param i The index in the outgoing edges * @return The edge id */ template<bool graphHasEdgeIds> inline edgeid getOutEdgeId(node u, index i) const; /** * Returns the edge id of the edge of index i in the incoming edges of node u * * @param u The node * @param i The index in the incoming edges of u * @return The edge id */ template<bool graphHasEdgeIds> inline edgeid getInEdgeId(node u, index i) const; /** * @brief Returns if the edge (u, v) shall be used in the iteration of all edgesIndexed * * @param u The source node of the edge * @param v The target node of the edge * @return If the node shall be used, i.e. if v is not none and in the undirected case if u >= v */ template<bool graphIsDirected> inline bool useEdgeInIteration(node u, node v) const; /** * @brief Implementation of the for loop for outgoing edges of u * * Note: If all (valid) outgoing edges shall be considered, graphIsDirected needs to be set to true * * @param u The node * @param handle The handle that shall be executed for each edge * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void forOutEdgesOfImpl(node u, L handle) const; /** * @brief Implementation of the for loop for incoming edges of u * * For undirected graphs, this is the same as forOutEdgesOfImpl but u and v are changed in the handle * * @param u The node * @param handle The handle that shall be executed for each edge * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void forInEdgesOfImpl(node u, L handle) const; /** * @brief Implementation of the for loop for all edges, @see forEdges * * @param handle The handle that shall be executed for all edges * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void forEdgeImpl(L handle) const; /** * @brief Parallel implementation of the for loop for all edges, @see parallelForEdges * * @param handle The handle that shall be executed for all edges * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void parallelForEdgesImpl(L handle) const; /** * @brief Summation variant of the parallel for loop for all edges, @see parallelSumForEdges * * @param handle The handle that shall be executed for all edges * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline double parallelSumForEdgesImpl(L handle) const; /* * In the following definition, Aux::FunctionTraits is used in order to only execute lambda functions * with the appropriate parameters. The decltype-return type is used for determining the return type of * the lambda (needed for summation) but also determines if the lambda accepts the correct number of parameters. * Otherwise the return type declaration fails and the function is excluded from overload resoluation. * Then there are multiple possible lambdas with three (third parameter id or weight) and two (second parameter * can be second node id or edge weight for neighbor iterators). This is checked using Aux::FunctionTraits and * std::enable_if. std::enable_if only defines the type member when the given bool is true, this bool comes from * std::is_same which compares two types. The function traits give either the parameter type or if it is out of bounds * they define type as void. */ /** * Triggers a static assert error when no other method is chosen. Because of the use of "..." as arguments, the priority * of this method is lower than the priority of the other methods. This method avoids ugly and unreadable template substitution * error messages from the other declarations. */ template<class F, void* = (void*)0> typename Aux::FunctionTraits<F>::result_type edgeLambda(F&, ...) const { // the strange condition is used in order to delay the eveluation of the static assert to the moment when this function is actually used static_assert(! std::is_same<F, F>::value, "Your lambda does not support the required parameters or the parameters have the wrong type."); return std::declval<typename Aux::FunctionTraits<F>::result_type>(); // use the correct return type (this won't compile) } /** * Calls the given function f if its fourth argument is of the type edgeid and third of type edgeweight * Note that the decltype check is not enough as edgeweight can be casted to node and we want to assure that . */ template < class F, typename std::enable_if < (Aux::FunctionTraits<F>::arity >= 3) && std::is_same<edgeweight, typename Aux::FunctionTraits<F>::template arg<2>::type>::value && std::is_same<edgeid, typename Aux::FunctionTraits<F>::template arg<3>::type>::value >::type * = (void*)0 > auto edgeLambda(F &f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(u, v, ew, id)) { return f(u, v, ew, id); } /** * Calls the given function f if its third argument is of the type edgeid, discards the edge weight * Note that the decltype check is not enough as edgeweight can be casted to node. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 2) && std::is_same<edgeid, typename Aux::FunctionTraits<F>::template arg<2>::type>::value && std::is_same<node, typename Aux::FunctionTraits<F>::template arg<1>::type>::value /* prevent f(v, weight, eid) */ >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight, edgeid id) const -> decltype(f(u, v, id)) { return f(u, v, id); } /** * Calls the given function f if its third argument is of type edgeweight, discards the edge id * Note that the decltype check is not enough as node can be casted to edgeweight. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 2) && std::is_same<edgeweight, typename Aux::FunctionTraits<F>::template arg<2>::type>::value >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid /*id*/) const -> decltype(f(u, v, ew)) { return f(u, v, ew); } /** * Calls the given function f if it has only two arguments and the second argument is of type node, * discards edge weight and id * Note that the decltype check is not enough as edgeweight can be casted to node. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 1) && std::is_same<node, typename Aux::FunctionTraits<F>::template arg<1>::type>::value >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight /*ew*/, edgeid /*id*/) const -> decltype(f(u, v)) { return f(u, v); } /** * Calls the given function f if it has only two arguments and the second argument is of type edgeweight, * discards the first node and the edge id * Note that the decltype check is not enough as edgeweight can be casted to node. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 1) && std::is_same<edgeweight, typename Aux::FunctionTraits<F>::template arg<1>::type>::value >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid /*id*/) const -> decltype(f(u, ew)) { return f(v, ew); } /** * Calls the given function f if it has only one argument, discards the first * node id, the edge weight and the edge id */ template<class F, void* = (void*)0> auto edgeLambda(F&f, node, node v, edgeweight, edgeid) const -> decltype(f(v)) { return f(v); } /** * Calls the given BFS handle with distance parameter */ template <class F> auto callBFSHandle(F &f, node u, count dist) const -> decltype(f(u, dist)) { return f(u, dist); } /** * Calls the given BFS handle without distance parameter */ template <class F> auto callBFSHandle(F &f, node u, count) const -> decltype(f(u)) { return f(u); } public: /** * Create a graph of @a n nodes. The graph has assignable edge weights if @a weighted is set to <code>true</code>. * If @a weighted is set to <code>false</code> each edge has edge weight 1.0 and any other weight assignment will * be ignored. * @param n Number of nodes. * @param weighted If set to <code>true</code>, the graph has edge weights. * @param directed If set to @c true, the graph will be directed. */ Graph(count n = 0, bool weighted = false, bool directed = false); Graph(const Graph& G, bool weighted, bool directed); /** * Generate a weighted graph from a list of edges. (Useful for small * graphs in unit tests that you do not want to read from a file.) * * @param[in] edges list of weighted edges */ Graph(std::initializer_list<WeightedEdge> edges); /** * Create a graph as copy of @a other. * @param other The graph to copy. */ Graph(const Graph& other) = default; /** Default move constructor */ Graph(Graph&& other) = default; /** Default destructor */ ~Graph() = default; /** Default move assignment operator */ Graph& operator=(Graph&& other) = default; /** Default copy assignment operator */ Graph& operator=(const Graph& other) = default; /** EDGE IDS **/ /** * Initially assign integer edge identifiers. * * @param force Force re-indexing of edges even if they have already been indexed */ void indexEdges(bool force = false); /** * Checks if edges have been indexed * * @return bool if edges have been indexed */ bool hasEdgeIds() const { return edgesIndexed; } /** * Get the id of the given edge. */ edgeid edgeId(node u, node v) const; /** * Get an upper bound for the edge ids in the graph. * @return An upper bound for the edge ids. */ index upperEdgeIdBound() const { return omega; } /** GRAPH INFORMATION **/ /** * Get the ID of this graph. The ID is a unique unsigned integer given to * every graph on construction. */ count getId() const { return id; } /** * Return the type of the graph. * Graph: not weighted, undirected * WeightedGraph: weighted, undirected * DirectedGraph: not weighted, directed * WeightedDirectedGraph: weighted, directed */ std::string typ() const; /** * Try to save some memory by shrinking internal data structures of the graph. Only run this * once you finished editing the graph. Otherwise it will cause unnecessary reallocation of * memory. */ void shrinkToFit(); /** * Compacts the adjacency arrays by re-using no longer neede slots from deleted edges. */ void compactEdges(); /** * Sorts the adjacency arrays by node id. While the running time is linear this * temporarily duplicates the memory. */ void sortEdges(); /** * Set name of graph to @a name. * @param name The name. */ void setName(std::string name) { this->name = name; } /* * Returns the name of the graph. * @return The name of the graph. */ std::string getName() const { return name; } /** * Returns a string representation of the graph. * @return A string representation. */ std::string toString() const; /* COPYING */ /* * Copies all nodes to a new graph * @return graph with the same nodes. */ Graph copyNodes() const; /* NODE MODIFIERS */ /** * Add a new node to the graph and return it. * @return The new node. */ node addNode(); /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Add a new node to the graph with coordinates @a x and @y and return it. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] node addNode(float x, float y); /** * Remove a node @a v and all incident edges from the graph. * * Incoming as well as outgoing edges will be removed. * * @param u Node. */ void removeNode(node v); /** * Check if node @a v exists in the graph. * * @param v Node. * @return @c true if @a v exists, @c false otherwise. */ bool hasNode(node v) const { return (v < z) && this->exists[v]; } /** * Restores a previously deleted node @a v with its previous id in the graph. * * @param v Node. * */ void restoreNode(node v); // SET OPERATIONS /** * Appends another graph to this graph as a new subgraph. Performs node * id remapping. * @param G [description] */ void append(const Graph& G); /** * Modifies this graph to be the union of it and another graph. * Nodes with the same ids are identified with each other. * @param G [description] */ void merge(const Graph& G); // SUBGRAPHS Graph subgraphFromNodes(const std::unordered_set<node>& nodes) const; /** NODE PROPERTIES **/ /** * Returns the number of outgoing neighbors of @a v. * * @param v Node. * @return The number of outgoing neighbors. */ count degree(node v) const { return outDeg[v]; } /** * Get the number of incoming neighbors of @a v. * * @param v Node. * @return The number of incoming neighbors. * @note If the graph is not directed, the outgoing degree is returned. */ count degreeIn(node v) const { return directed ? inDeg[v] : outDeg[v]; } /** * Get the number of outgoing neighbors of @a v. * * @param v Node. * @return The number of outgoing neighbors. */ count degreeOut(node v) const { return outDeg[v]; } /** * Check whether @a v is isolated, i.e. degree is 0. * @param v Node. * @return @c true if the node is isolated (= degree is 0) */ bool isIsolated(node v) const { return outDeg[v] == 0 && (!directed || inDeg[v] == 0); } /** * Returns the weighted degree of @a v. * * @param v Node. * @return Weighted degree of @a v. * @note For directed graphs this is the sum of weights of all outgoing edges of @a v. */ edgeweight weightedDegree(node v) const; /** * Returns the volume of the @a v, which is the weighted degree with self-loops counted twice. * * @param v Node. * @return The volume of the @a v. */ edgeweight volume(node v) const; /** * Returns a random node of the graph. * @return A random node. */ node randomNode() const; /** * Returns a random neighbor of @a u and @c none if degree is zero. * * @param u Node. * @return A random neighbor of @a u. */ node randomNeighbor(node u) const; /* EDGE MODIFIERS */ /** * Insert an edge between the nodes @a u and @a v. If the graph is weighted you can optionally * set a weight for this edge. The default weight is 1.0. * Note: Multi-edges are not supported and will NOT be handled consistently by the graph data * structure. * @param u Endpoint of edge. * @param v Endpoint of edge. * @param weight Optional edge weight. */ void addEdge(node u, node v, edgeweight ew = defaultEdgeWeight); /** * Removes the undirected edge {@a u,@a v}. * @param u Endpoint of edge. * @param v Endpoint of edge. */ void removeEdge(node u, node v); /** * Removes all the edges in the graph. */ void removeAllEdges(); /** * Removes all self-loops in the graph. */ void removeSelfLoops(); /** * Changes the edges {@a s1, @a t1} into {@a s1, @a t2} and the edge {@a s2, @a t2} into {@a s2, @a t1}. * * If there are edge weights or edge ids, they are preserved. Note that no check is performed if the swap is actually possible, i.e. does not generate duplicate edges. * * @param s1 The first source * @param t1 The first target * @param s2 The second source * @param t2 The second target */ void swapEdge(NetworKit::node s1, NetworKit::node t1, NetworKit::node s2, NetworKit::node t2); /** * Checks if undirected edge {@a u,@a v} exists in the graph. * @param u Endpoint of edge. * @param v Endpoint of edge. * @return <code>true</code> if the edge exists, <code>false</code> otherwise. */ bool hasEdge(node u, node v) const; /** * Returns a random edge. By default a random node u is chosen and then some random neighbor v. So the probability of choosing (u, v) highly * depends on the degree of u. * Setting uniformDistribution to true, will give you a real uniform distributed edge, but will be very slow. So only use uniformDistribution * for single calls outside of any loops. */ std::pair<node, node> randomEdge(bool uniformDistribution = false) const; /** * Returns a vector with nr random edges. The edges are chosen uniform random. */ std::vector< std::pair<node, node> > randomEdges(count nr) const; /* GLOBAL PROPERTIES */ /** * Returns <code>true</code> if this graph supports edge weights other than 1.0. * @return <code>true</code> if this graph supports edge weights other than 1.0. */ bool isWeighted() const { return weighted; } /** * Return @c true if this graph supports directed edges. * @return @c true if this graph supports directed edges. */ bool isDirected() const { return directed; } /** * Return <code>true</code> if graph contains no nodes. * @return <code>true</code> if graph contains no nodes. */ bool isEmpty() const { return n == 0; } /** * Return the number of nodes in the graph. * @return The number of nodes. */ count numberOfNodes() const { return n; } /** * Return the number of edges in the graph. * @return The number of edges. */ count numberOfEdges() const { return m; } /** * @return a pair (n, m) where n is the number of nodes and m is the number of edges */ std::pair<count, count> const size() const { return {n, m}; }; /** * @return the density of the graph */ double density() const { count n = numberOfNodes(); count m = numberOfEdges(); count loops = numberOfSelfLoops(); m -= loops; double d; if (isDirected()) { d = m / (double) (n * (n-1)); } else { d = (2 * m) / (double) (n * (n-1)); } return d; } /** * Return the number of loops {v,v} in the graph. * @return The number of loops. * @note This involves calculation, so store result if needed multiple times. */ count numberOfSelfLoops() const; /** * Get an upper bound for the node ids in the graph. * @return An upper bound for the node ids. */ index upperNodeIdBound() const { return z; } /** * Check for invalid graph states, such as multi-edges. * @return False if the graph is in invalid state. */ bool checkConsistency() const; /* DYNAMICS */ /** * Trigger a time step - increments counter. */ void timeStep() { t++; } /** * Get time step counter. * @return Time step counter. */ count time() { return t; } /* COORDINATES */ /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Sets the coordinate of @a v to @a value. * * @param v Node. * @param value The coordinate of @a v. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] void setCoordinate(node v, Point<float> value) { coordinates.setCoordinate(v, value); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Get the coordinate of @a v. * @param v Node. * @return The coordinate of @a v. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] Point<float>& getCoordinate(node v) { return coordinates.getCoordinate(v); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Get minimum coordinate of all coordinates with respect to dimension @a dim. * @param dim The dimension to search for minimum. * @return The minimum coordinate in dimension @a dim. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] float minCoordinate(count dim) { return coordinates.minCoordinate(dim); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Get maximum coordinate of all coordinates with respect to dimension @a dim. * @param dim The dimension to search for maximum. * @return The maximum coordinate in dimension @a dim. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] float maxCoordinate(count dim) { return coordinates.maxCoordinate(dim); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Initializes the coordinates for the nodes in graph. * @note This has to be called once and before you set coordinates. Call this method again if new nodes have * been added. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] void initCoordinates() { coordinates.init(z); } /* EDGE ATTRIBUTES */ /** * Return edge weight of edge {@a u,@a v}. Returns 0 if edge does not exist. * BEWARE: Running time is \Theta(deg(u))! * * @param u Endpoint of edge. * @param v Endpoint of edge. * @return Edge weight of edge {@a u,@a v} or 0 if edge does not exist. */ edgeweight weight(node u, node v) const; /** * Set the weight of an edge. If the edge does not exist, * it will be inserted. * * @param[in] u endpoint of edge * @param[in] v endpoint of edge * @param[in] weight edge weight */ void setWeight(node u, node v, edgeweight ew); /** * Increase the weight of an edge. If the edge does not exist, * it will be inserted. * * @param[in] u endpoint of edge * @param[in] v endpoint of edge * @param[in] weight edge weight */ void increaseWeight(node u, node v, edgeweight ew); /* SUMS */ /** * Returns the sum of all edge weights. * @return The sum of all edge weights. */ edgeweight totalEdgeWeight() const; /* Collections */ /** * Get list of all nodes. * @return List of all nodes. */ std::vector<node> nodes() const; /** * Get list of edges as node pairs. * @return List of edges as node pairs. */ std::vector<std::pair<node, node> > edges() const; /** * Get list of neighbors of @a u. * * @param u Node. * @return List of neighbors of @a u. */ std::vector<node> neighbors(node u) const; /** * Get i-th (outgoing) neighbor of @a u. * WARNING: This function is deprecated or only temporary. * * @param u Node. * @param i index; should be in [0, degreeOut(u)) * @return @a i -th (outgoing) neighbor of @a u, or @c none if no such * neighbor exists. */ template<bool graphIsDirected> node getIthNeighbor(node u, index i) const { node v = outEdges[u][i]; if (useEdgeInIteration<graphIsDirected>(u, v)) return v; else return none; } /* Derivative Graphs */ /** * Return an undirected version of this graph. * * @return undirected graph. */ Graph toUndirected() const; /** * Return an unweighted version of this graph. * * @return unweighted graph. */ Graph toUnweighted() const; /** * Return the transpose of this graph. The graph must be directed. * * @return transpose of the graph. */ Graph transpose() const; /* NODE ITERATORS */ /** * Iterate over all nodes of the graph and call @a handle (lambda closure). * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void forNodes(L handle) const; /** * Iterate randomly over all nodes of the graph and call @a handle (lambda closure). * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void parallelForNodes(L handle) const; /** Iterate over all nodes of the graph and call @a handle (lambda closure) as long as @a condition remains true. * This allows for breaking from a node loop. * * @param condition Returning <code>false</code> breaks the loop. * @param handle Takes parameter <code>(node)</code>. */ template<typename C, typename L> void forNodesWhile(C condition, L handle) const; /** * Iterate randomly over all nodes of the graph and call @a handle (lambda closure). * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void forNodesInRandomOrder(L handle) const; /** * Iterate in parallel over all nodes of the graph and call handler (lambda closure). * Using schedule(guided) to remedy load-imbalances due to e.g. unequal degree distribution. * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void balancedParallelForNodes(L handle) const; /** * Iterate over all undirected pairs of nodes and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code>. */ template<typename L> void forNodePairs(L handle) const; /** * Iterate over all undirected pairs of nodes in parallel and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code>. */ template<typename L> void parallelForNodePairs(L handle) const; /* EDGE ITERATORS */ /** * Iterate over all edges of the const graph and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code>, <code>(node, node, edgweight)</code>, <code>(node, node, edgeid)</code> or <code>(node, node, edgeweight, edgeid)</code>. */ template<typename L> void forEdges(L handle) const; /** * Iterate in parallel over all edges of the const graph and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code> or <code>(node, node, edgweight)</code>, <code>(node, node, edgeid)</code> or <code>(node, node, edgeweight, edgeid)</code>. */ template<typename L> void parallelForEdges(L handle) const; /* NEIGHBORHOOD ITERATORS */ /** * Iterate over all neighbors of a node and call @a handle (lamdba closure). * * @param u Node. * @param handle Takes parameter <code>(node)</code> or <code>(node, edgeweight)</code> which is a neighbor of @a u. * @note For directed graphs only outgoing edges from @a u are considered. * A node is its own neighbor if there is a self-loop. * */ template<typename L> void forNeighborsOf(node u, L handle) const; /** * Iterate over all incident edges of a node and call @a handle (lamdba closure). * * @param u Node. * @param handle Takes parameters <code>(node, node)</code>, <code>(node, node, edgeweight)</code>, <code>(node, node, edgeid)</code> or <code>(node, node, edgeweight, edgeid)</code> where the first node is @a u and the second is a neighbor of @a u. * @note For undirected graphs all edges incident to @a u are also outgoing edges. */ template<typename L> void forEdgesOf(node u, L handle) const; /** * Iterate over all neighbors of a node and call handler (lamdba closure). * For directed graphs only incoming edges from u are considered. */ template<typename L> void forInNeighborsOf(node u, L handle) const; /** * Iterate over all incoming edges of a node and call handler (lamdba closure). * @note For undirected graphs all edges incident to u are also incoming edges. * * Handle takes parameters (u, v) or (u, v, w) where w is the edge weight. */ template<typename L> void forInEdgesOf(node u, L handle) const; /* REDUCTION ITERATORS */ /** * Iterate in parallel over all nodes and sum (reduce +) the values returned by the handler */ template<typename L> double parallelSumForNodes(L handle) const; /** * Iterate in parallel over all edges and sum (reduce +) the values returned by the handler */ template<typename L> double parallelSumForEdges(L handle) const; /* GRAPH SEARCHES */ /** * Iterate over nodes in breadth-first search order starting from r until connected component * of r has been visited. * * @param r Node. * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void BFSfrom(node r, L handle) const; template<typename L> void BFSfrom(const std::vector<node> &startNodes, L handle) const; template<typename L> void BFSEdgesFrom(node r, L handle) const; /** * Iterate over nodes in depth-first search order starting from r until connected component * of r has been visited. * * @param r Node. * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void DFSfrom(node r, L handle) const; template<typename L> void DFSEdgesFrom(node r, L handle) const; }; /* NODE ITERATORS */ template<typename L> void Graph::forNodes(L handle) const { for (node v = 0; v < z; ++v) { if (exists[v]) { handle(v); } } } template<typename L> void Graph::parallelForNodes(L handle) const { #pragma omp parallel for for (omp_index v = 0; v < static_cast<omp_index>(z); ++v) { if (exists[v]) { handle(v); } } } template<typename C, typename L> void Graph::forNodesWhile(C condition, L handle) const { for (node v = 0; v < z; ++v) { if (exists[v]) { if (!condition()) { break; } handle(v); } } } template<typename L> void Graph::forNodesInRandomOrder(L handle) const { std::vector<node> randVec = nodes(); std::shuffle(randVec.begin(), randVec.end(), Aux::Random::getURNG()); for (node v : randVec) { handle(v); } } template<typename L> void Graph::balancedParallelForNodes(L handle) const { #pragma omp parallel for schedule(guided) // TODO: define min block size (and test it!) for (omp_index v = 0; v < static_cast<omp_index>(z); ++v) { if (exists[v]) { handle(v); } } } template<typename L> void Graph::forNodePairs(L handle) const { for (node u = 0; u < z; ++u) { if (exists[u]) { for (node v = u + 1; v < z; ++v) { if (exists[v]) { handle(u, v); } } } } } template<typename L> void Graph::parallelForNodePairs(L handle) const { #pragma omp parallel for schedule(guided) for (omp_index u = 0; u < static_cast<omp_index>(z); ++u) { if (exists[u]) { for (node v = u + 1; v < z; ++v) { if (exists[v]) { handle(u, v); } } } } } /* EDGE ITERATORS */ /* HELPERS */ template<bool hasWeights> // implementation for weighted == true inline edgeweight Graph::getOutEdgeWeight(node u, index i) const { return outEdgeWeights[u][i]; } template<> // implementation for weighted == false inline edgeweight Graph::getOutEdgeWeight<false>(node, index) const { return defaultEdgeWeight; } template<bool hasWeights> // implementation for weighted == true inline edgeweight Graph::getInEdgeWeight(node u, index i) const { return inEdgeWeights[u][i]; } template<> // implementation for weighted == false inline edgeweight Graph::getInEdgeWeight<false>(node, index) const { return defaultEdgeWeight; } template<bool graphHasEdgeIds> // implementation for hasEdgeIds == true inline edgeid Graph::getOutEdgeId(node u, index i) const { return outEdgeIds[u][i]; } template<> // implementation for hasEdgeIds == false inline edgeid Graph::getOutEdgeId<false>(node, index) const { return 0; } template<bool graphHasEdgeIds> // implementation for hasEdgeIds == true inline edgeid Graph::getInEdgeId(node u, index i) const { return inEdgeIds[u][i]; } template<> // implementation for hasEdgeIds == false inline edgeid Graph::getInEdgeId<false>(node, index) const { return 0; } template<bool graphIsDirected> // implementation for graphIsDirected == true inline bool Graph::useEdgeInIteration(node /* u */, node v) const { return v != none; } template<> // implementation for graphIsDirected == false inline bool Graph::useEdgeInIteration<false>(node u, node v) const { return u >= v; } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::forOutEdgesOfImpl(node u, L handle) const { for (index i = 0; i < outEdges[u].size(); ++i) { node v = outEdges[u][i]; if (useEdgeInIteration<graphIsDirected>(u, v)) { edgeLambda<L>(handle, u, v, getOutEdgeWeight<hasWeights>(u, i), getOutEdgeId<graphHasEdgeIds>(u, i)); } } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::forInEdgesOfImpl(node u, L handle) const { if (graphIsDirected) { for (index i = 0; i < inEdges[u].size(); i++) { node v = inEdges[u][i]; if (useEdgeInIteration<true>(u, v)) { edgeLambda<L>(handle, u, v, getInEdgeWeight<hasWeights>(u, i), getInEdgeId<graphHasEdgeIds>(u, i)); } } } else { for (index i = 0; i < outEdges[u].size(); ++i) { node v = outEdges[u][i]; if (useEdgeInIteration<true>(u, v)) { edgeLambda<L>(handle, u, v, getOutEdgeWeight<hasWeights>(u, i), getOutEdgeId<graphHasEdgeIds>(u, i)); } } } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::forEdgeImpl(L handle) const { for (node u = 0; u < z; ++u) { forOutEdgesOfImpl<graphIsDirected, hasWeights, graphHasEdgeIds, L>(u, handle); } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::parallelForEdgesImpl(L handle) const { #pragma omp parallel for schedule(guided) for (omp_index u = 0; u < static_cast<omp_index>(z); ++u) { forOutEdgesOfImpl<graphIsDirected, hasWeights, graphHasEdgeIds, L>(u, handle); } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline double Graph::parallelSumForEdgesImpl(L handle) const { double sum = 0.0; #pragma omp parallel for reduction(+:sum) for (omp_index u = 0; u < static_cast<omp_index>(z); ++u) { for (index i = 0; i < outEdges[u].size(); ++i) { node v = outEdges[u][i]; // undirected, do not iterate over edges twice // {u, v} instead of (u, v); if v == none, u > v is not fulfilled if (useEdgeInIteration<graphIsDirected>(u, v)) { sum += edgeLambda<L>(handle, u, v, getOutEdgeWeight<hasWeights>(u, i), getOutEdgeId<graphHasEdgeIds>(u, i)); } } } return sum; } template<typename L> void Graph::forEdges(L handle) const { switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: // unweighted, undirected, no edgeIds forEdgeImpl<false, false, false, L>(handle); break; case 1: // weighted, undirected, no edgeIds forEdgeImpl<false, true, false, L>(handle); break; case 2: // unweighted, directed, no edgeIds forEdgeImpl<true, false, false, L>(handle); break; case 3: // weighted, directed, no edgeIds forEdgeImpl<true, true, false, L>(handle); break; case 4: // unweighted, undirected, with edgeIds forEdgeImpl<false, false, true, L>(handle); break; case 5: // weighted, undirected, with edgeIds forEdgeImpl<false, true, true, L>(handle); break; case 6: // unweighted, directed, with edgeIds forEdgeImpl<true, false, true, L>(handle); break; case 7: // weighted, directed, with edgeIds forEdgeImpl<true, true, true, L>(handle); break; } } template<typename L> void Graph::parallelForEdges(L handle) const { switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: // unweighted, undirected, no edgeIds parallelForEdgesImpl<false, false, false, L>(handle); break; case 1: // weighted, undirected, no edgeIds parallelForEdgesImpl<false, true, false, L>(handle); break; case 2: // unweighted, directed, no edgeIds parallelForEdgesImpl<true, false, false, L>(handle); break; case 3: // weighted, directed, no edgeIds parallelForEdgesImpl<true, true, false, L>(handle); break; case 4: // unweighted, undirected, with edgeIds parallelForEdgesImpl<false, false, true, L>(handle); break; case 5: // weighted, undirected, with edgeIds parallelForEdgesImpl<false, true, true, L>(handle); break; case 6: // unweighted, directed, with edgeIds parallelForEdgesImpl<true, false, true, L>(handle); break; case 7: // weighted, directed, with edgeIds parallelForEdgesImpl<true, true, true, L>(handle); break; } } /* NEIGHBORHOOD ITERATORS */ template<typename L> void Graph::forNeighborsOf(node u, L handle) const { forEdgesOf(u, handle); } template<typename L> void Graph::forEdgesOf(node u, L handle) const { switch (weighted + 2 * edgesIndexed) { case 0: //not weighted, no edge ids forOutEdgesOfImpl<true, false, false, L>(u, handle); break; case 1: //weighted, no edge ids forOutEdgesOfImpl<true, true, false, L>(u, handle); break; case 2: //not weighted, with edge ids forOutEdgesOfImpl<true, false, true, L>(u, handle); break; case 3: //weighted, with edge ids forOutEdgesOfImpl<true, true, true, L>(u, handle); break; } } template<typename L> void Graph::forInNeighborsOf(node u, L handle) const { forInEdgesOf(u, handle); } template<typename L> void Graph::forInEdgesOf(node u, L handle) const { switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: //unweighted, undirected, no edge ids forInEdgesOfImpl<false, false, false, L>(u, handle); break; case 1: //weighted, undirected, no edge ids forInEdgesOfImpl<false, true, false, L>(u, handle); break; case 2: //unweighted, directed, no edge ids forInEdgesOfImpl<true, false, false, L>(u, handle); break; case 3: //weighted, directed, no edge ids forInEdgesOfImpl<true, true, false, L>(u, handle); break; case 4: //unweighted, undirected, with edge ids forInEdgesOfImpl<false, false, true, L>(u, handle); break; case 5: //weighted, undirected, with edge ids forInEdgesOfImpl<false, true, true, L>(u, handle); break; case 6: //unweighted, directed, with edge ids forInEdgesOfImpl<true, false, true, L>(u, handle); break; case 7: //weighted, directed, with edge ids forInEdgesOfImpl<true, true, true, L>(u, handle); break; } } /* REDUCTION ITERATORS */ template<typename L> double Graph::parallelSumForNodes(L handle) const { double sum = 0.0; #pragma omp parallel for reduction(+:sum) for (omp_index v = 0; v < static_cast<omp_index>(z); ++v) { if (exists[v]) { sum += handle(v); } } return sum; } template<typename L> double Graph::parallelSumForEdges(L handle) const { double sum = 0.0; switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: // unweighted, undirected, no edge ids sum = parallelSumForEdgesImpl<false, false, false, L>(handle); break; case 1: // weighted, undirected, no edge ids sum = parallelSumForEdgesImpl<false, true, false, L>(handle); break; case 2: // unweighted, directed, no edge ids sum = parallelSumForEdgesImpl<true, false, false, L>(handle); break; case 3: // weighted, directed, no edge ids sum = parallelSumForEdgesImpl<true, true, false, L>(handle); break; case 4: // unweighted, undirected, with edge ids sum = parallelSumForEdgesImpl<false, false, true, L>(handle); break; case 5: // weighted, undirected, with edge ids sum = parallelSumForEdgesImpl<false, true, true, L>(handle); break; case 6: // unweighted, directed, with edge ids sum = parallelSumForEdgesImpl<true, false, true, L>(handle); break; case 7: // weighted, directed, with edge ids sum = parallelSumForEdgesImpl<true, true, true, L>(handle); break; } return sum; } /* GRAPH SEARCHES */ template<typename L> void Graph::BFSfrom(node r, L handle) const { std::vector<node> startNodes(1, r); BFSfrom(startNodes, handle); } template<typename L> void Graph::BFSfrom(const std::vector<node> &startNodes, L handle) const { std::vector<bool> marked(z); std::queue<node> q, qNext; count dist = 0; // enqueue start nodes for (node u : startNodes) { q.push(u); marked[u] = true; } do { node u = q.front(); q.pop(); // apply function callBFSHandle(handle, u, dist); forNeighborsOf(u, [&](node v) { if (!marked[v]) { qNext.push(v); marked[v] = true; } }); if (q.empty() && !qNext.empty()) { q.swap(qNext); ++dist; } } while (!q.empty()); } template<typename L> void Graph::BFSEdgesFrom(node r, L handle) const { std::vector<bool> marked(z); std::queue<node> q; q.push(r); // enqueue root marked[r] = true; do { node u = q.front(); q.pop(); // apply function forNeighborsOf(u, [&](node, node v, edgeweight w, edgeid eid) { if (!marked[v]) { handle(u, v, w, eid); q.push(v); marked[v] = true; } }); } while (!q.empty()); } template<typename L> void Graph::DFSfrom(node r, L handle) const { std::vector<bool> marked(z); std::stack<node> s; s.push(r); // enqueue root marked[r] = true; do { node u = s.top(); s.pop(); // apply function handle(u); forNeighborsOf(u, [&](node v) { if (!marked[v]) { s.push(v); marked[v] = true; } }); } while (!s.empty()); } template<typename L> void Graph::DFSEdgesFrom(node r, L handle) const { std::vector<bool> marked(z); std::stack<node> s; s.push(r); // enqueue root marked[r] = true; do { node u = s.top(); s.pop(); // apply function forNeighborsOf(u, [&](node v) { if (!marked[v]) { handle(u, v); s.push(v); marked[v] = true; } }); } while (!s.empty()); } } /* namespace NetworKit */ #endif /* GRAPH_H_ */
GB_split_sparse.c
//------------------------------------------------------------------------------ // GB_split_sparse: split a sparse/hypersparse matrix into tiles //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #define GB_FREE_WORKSPACE \ GB_WERK_POP (C_ek_slicing, int64_t) ; \ GB_FREE_WORK (&Wp, Wp_size) ; #define GB_FREE_ALL \ GB_FREE_WORKSPACE ; \ GB_Matrix_free (&C) ; #include "GB_split.h" GrB_Info GB_split_sparse // split a sparse matrix ( GrB_Matrix *Tiles, // 2D row-major array of size m-by-n const GrB_Index m, const GrB_Index n, const int64_t *restrict Tile_rows, // size m+1 const int64_t *restrict Tile_cols, // size n+1 const GrB_Matrix A, // input matrix GB_Context Context ) { //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GrB_Info info ; int A_sparsity = GB_sparsity (A) ; bool A_is_hyper = (A_sparsity == GxB_HYPERSPARSE) ; ASSERT (A_is_hyper || A_sparsity == GxB_SPARSE) ; GrB_Matrix C = NULL ; GB_WERK_DECLARE (C_ek_slicing, int64_t) ; ASSERT_MATRIX_OK (A, "A sparse for split", GB0) ; int sparsity_control = A->sparsity_control ; float hyper_switch = A->hyper_switch ; bool csc = A->is_csc ; GrB_Type atype = A->type ; int64_t avlen = A->vlen ; int64_t avdim = A->vdim ; size_t asize = atype->size ; GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int64_t nouter = csc ? n : m ; int64_t ninner = csc ? m : n ; const int64_t *Tile_vdim = csc ? Tile_cols : Tile_rows ; const int64_t *Tile_vlen = csc ? Tile_rows : Tile_cols ; int64_t anvec = A->nvec ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; const bool A_iso = A->iso ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- size_t Wp_size = 0 ; int64_t *restrict Wp = NULL ; Wp = GB_MALLOC_WORK (anvec, int64_t, &Wp_size) ; if (Wp == NULL) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } GB_memcpy (Wp, Ap, anvec * sizeof (int64_t), nthreads_max) ; //-------------------------------------------------------------------------- // split A into tiles //-------------------------------------------------------------------------- int64_t akend = 0 ; for (int64_t outer = 0 ; outer < nouter ; outer++) { //---------------------------------------------------------------------- // find the starting and ending vector of these tiles //---------------------------------------------------------------------- // The tile appears in vectors avstart:avend-1 of A, and indices // aistart:aiend-1. const int64_t avstart = Tile_vdim [outer] ; const int64_t avend = Tile_vdim [outer+1] ; int64_t akstart = akend ; if (A_is_hyper) { // A is hypersparse: look for vector avend in the A->h hyper list. // The vectors to handle for this outer loop are in // Ah [akstart:akend-1]. akend = akstart ; int64_t pright = anvec - 1 ; bool found ; GB_SPLIT_BINARY_SEARCH (avend, Ah, akend, pright, found) ; ASSERT (GB_IMPLIES (akstart <= akend-1, Ah [akend-1] < avend)) ; } else { // A is sparse; the vectors to handle are akstart:akend-1 akend = avend ; } // # of vectors in all tiles in this outer loop int64_t cnvec = akend - akstart ; int nth = GB_nthreads (cnvec, chunk, nthreads_max) ; //---------------------------------------------------------------------- // create all tiles for vectors akstart:akend-1 in A //---------------------------------------------------------------------- for (int64_t inner = 0 ; inner < ninner ; inner++) { //------------------------------------------------------------------ // allocate C, C->p, and C->h for this tile //------------------------------------------------------------------ const int64_t aistart = Tile_vlen [inner] ; const int64_t aiend = Tile_vlen [inner+1] ; const int64_t cvdim = avend - avstart ; const int64_t cvlen = aiend - aistart ; C = NULL ; GB_OK (GB_new (&C, false, // new header atype, cvlen, cvdim, GB_Ap_malloc, csc, A_sparsity, hyper_switch, cnvec, Context)) ; C->sparsity_control = sparsity_control ; C->hyper_switch = hyper_switch ; C->nvec = cnvec ; int64_t *restrict Cp = C->p ; int64_t *restrict Ch = C->h ; //------------------------------------------------------------------ // determine the boundaries of this tile //------------------------------------------------------------------ int64_t k ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = akstart ; k < akend ; k++) { int64_t pA = Wp [k] ; const int64_t pA_end = Ap [k+1] ; const int64_t aknz = pA_end - pA ; if (aknz == 0 || Ai [pA] >= aiend) { // this vector of C is empty } else if (aknz > 256) { // use binary search to find aiend bool found ; int64_t pright = pA_end - 1 ; GB_SPLIT_BINARY_SEARCH (aiend, Ai, pA, pright, found) ; #ifdef GB_DEBUG // check the results with a linear search int64_t p2 = Wp [k] ; for ( ; p2 < Ap [k+1] ; p2++) { if (Ai [p2] >= aiend) break ; } ASSERT (pA == p2) ; #endif } else { // use a linear-time search to find aiend for ( ; pA < pA_end ; pA++) { if (Ai [pA] >= aiend) break ; } #ifdef GB_DEBUG // check the results with a binary search bool found ; int64_t p2 = Wp [k] ; int64_t p2_end = Ap [k+1] - 1 ; GB_SPLIT_BINARY_SEARCH (aiend, Ai, p2, p2_end, found) ; ASSERT (pA == p2) ; #endif } Cp [k-akstart] = (pA - Wp [k]) ; // # of entries in this vector if (A_is_hyper) { Ch [k-akstart] = Ah [k] - avstart ; } } GB_cumsum (Cp, cnvec, &(C->nvec_nonempty), nth, Context) ; int64_t cnz = Cp [cnvec] ; //------------------------------------------------------------------ // allocate C->i and C->x for this tile //------------------------------------------------------------------ // set C->iso = A_iso OK GB_OK (GB_bix_alloc (C, cnz, GxB_SPARSE, false, true, A_iso, Context)) ; int64_t *restrict Ci = C->i ; C->magic = GB_MAGIC ; // for GB_nnz_held(C), to slice C //------------------------------------------------------------------ // copy the tile from A into C //------------------------------------------------------------------ int C_ntasks, C_nthreads ; GB_SLICE_MATRIX (C, 8, chunk) ; bool done = false ; if (A_iso) { //-------------------------------------------------------------- // split an iso matrix A into an iso tile C //-------------------------------------------------------------- // A is iso and so is C; copy the iso entry GBURBLE ("(iso sparse split) ") ; memcpy (C->x, A->x, asize) ; #define GB_ISO_SPLIT #define GB_COPY(pC,pA) ; #include "GB_split_sparse_template.c" } else { //-------------------------------------------------------------- // split a non-iso matrix A into an non-iso tile C //-------------------------------------------------------------- #ifndef GBCOMPACT // no typecasting needed switch (asize) { #undef GB_COPY #define GB_COPY(pC,pA) Cx [pC] = Ax [pA] ; case GB_1BYTE : // uint8, int8, bool, or 1-byte user-defined #define GB_CTYPE uint8_t #include "GB_split_sparse_template.c" break ; case GB_2BYTE : // uint16, int16, or 2-byte user-defined #define GB_CTYPE uint16_t #include "GB_split_sparse_template.c" break ; case GB_4BYTE : // uint32, int32, float, or 4-byte user #define GB_CTYPE uint32_t #include "GB_split_sparse_template.c" break ; case GB_8BYTE : // uint64, int64, double, float complex, // or 8-byte user defined #define GB_CTYPE uint64_t #include "GB_split_sparse_template.c" break ; case GB_16BYTE : // double complex or 16-byte user-defined #define GB_CTYPE GB_blob16 // #define GB_CTYPE uint64_t // #undef GB_COPY // #define GB_COPY(pC,pA) \ // Cx [2*pC ] = Ax [2*pA ] ; \ // Cx [2*pC+1] = Ax [2*pA+1] ; #include "GB_split_sparse_template.c" break ; default:; } #endif } if (!done) { // user-defined types #define GB_CTYPE GB_void #undef GB_COPY #define GB_COPY(pC,pA) \ memcpy (Cx + (pC)*asize, Ax +(pA)*asize, asize) ; #include "GB_split_sparse_template.c" } //------------------------------------------------------------------ // free workspace //------------------------------------------------------------------ GB_WERK_POP (C_ek_slicing, int64_t) ; //------------------------------------------------------------------ // advance to the next tile //------------------------------------------------------------------ if (inner < ninner - 1) { int64_t k ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = akstart ; k < akend ; k++) { int64_t ck = k - akstart ; int64_t cknz = Cp [ck+1] - Cp [ck] ; Wp [k] += cknz ; } } //------------------------------------------------------------------ // conform the tile and save it in the Tiles array //------------------------------------------------------------------ ASSERT_MATRIX_OK (C, "C for GB_split", GB0) ; GB_OK (GB_hypermatrix_prune (C, Context)) ; GB_OK (GB_conform (C, Context)) ; if (csc) { GB_TILE (Tiles, inner, outer) = C ; } else { GB_TILE (Tiles, outer, inner) = C ; } ASSERT_MATRIX_OK (C, "final tile C for GB_split", GB0) ; C = NULL ; } } GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; }
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 *restrict r_Schw_arr,REAL *restrict rho_arr,REAL *restrict rho_baryon_arr,REAL *restrict P_arr, REAL *restrict M_arr,REAL *restrict expnu_arr,REAL *restrict exp4phi_arr,REAL *restrict 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 ); rho_baryon_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; } // Find interpolation index using Bisection root-finding algorithm: static inline int bisection_idx_finder(const REAL rrbar, const int numlines_in_file, const REAL *restrict 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",rrbar,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); } 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 *restrict r_Schw_arr,const REAL *restrict rho_arr,const REAL *restrict rho_baryon_arr,const REAL *restrict P_arr, const REAL *restrict M_arr,const REAL *restrict expnu_arr,const REAL *restrict exp4phi_arr,const REAL *restrict rbar_arr, REAL *restrict rho,REAL *restrict rho_baryon,REAL *restrict P,REAL *restrict M,REAL *restrict expnu,REAL *restrict exp4phi) { // 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; *rho_baryon = 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]; *rho_baryon += l_i_of_r[i-idxmin] * rho_baryon_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; *rho_baryon = 0; *P = 0; *M = M_arr[Rbar_idx+1]; *expnu = 1. - 2.*(*M) / r_Schw; *exp4phi = pow(r_Schw / rrbar,2.0); } } // To compile, copy this file to tov_interp.c, and then run: // gcc -Ofast tov_interp.c -o tov_interp -DSTANDALONE_UNIT_TEST #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 *rho_baryon_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,rho_baryon_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,rho_baryon,P,M,expnu,exp4phi; TOV_interpolate_1D(rrbar,Rbar,Rbar_idx,4, numlines_in_file,r_Schw_arr,rho_arr,rho_baryon_arr,P_arr,M_arr,expnu_arr,exp4phi_arr,rbar_arr, &rho,&rho_baryon,&P,&M,&expnu,&exp4phi); printf("%e %e %e %e %e %e %e\n",rrbar,rho,rho_baryon,P,M,expnu,exp4phi); } // Free the malloc()'s! free(r_Schw_arr); free(rho_arr); free(rho_baryon_arr); free(P_arr); free(M_arr); free(expnu_arr); free(exp4phi_arr); free(rbar_arr); return 0; } #endif
determinantOfNcrossNMatrix.c
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <omp.h> #define SIZE 10 int main(){ float mat[SIZE][SIZE], ratio, det = 1; int i,j,k,n; printf("Enter Matrix Dimension = "); scanf("%d", &n); printf("\nEnter Elements: \n"); for(i = 0; i < n; i++){ for(j = 0; j < n;j++){ printf("mat[%d][%d] = ", i, j); scanf("%f", &mat[i][j]); } } printf("\nMatrix: \n"); for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ printf("%0.2f\t", mat[i][j]); } printf("\n"); } for(i = 0; i < n; i++){ if(mat[i][i] == 0.0){ printf("Mathematical Error!"); exit(0); } for(j = i + 1; j < n; j++){ ratio = mat[j][i] / mat[i][i]; for(k = 0; k < n; k++){ mat[j][k] = mat[j][k] - ratio * mat[i][k]; } } } #pragma omp parallel for shared(mat) private(i) reduction(*:det) for(i = 0; i < n; i++){ det *= mat[i][i]; } printf("\nDeterminant of given matrix is: %0.3f\n", det); return 0; }
GB_binop__le_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__le_int64) // A.*B function (eWiseMult): GB (_AemultB_08__le_int64) // A.*B function (eWiseMult): GB (_AemultB_02__le_int64) // A.*B function (eWiseMult): GB (_AemultB_04__le_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__le_int64) // A*D function (colscale): GB (_AxD__le_int64) // D*A function (rowscale): GB (_DxB__le_int64) // C+=B function (dense accum): GB (_Cdense_accumB__le_int64) // C+=b function (dense accum): GB (_Cdense_accumb__le_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__le_int64) // C=scalar+B GB (_bind1st__le_int64) // C=scalar+B' GB (_bind1st_tran__le_int64) // C=A+scalar GB (_bind2nd__le_int64) // C=A'+scalar GB (_bind2nd_tran__le_int64) // C type: bool // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x <= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LE || GxB_NO_INT64 || GxB_NO_LE_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__le_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__le_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__le_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__le_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__le_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__le_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__le_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__le_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__le_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__le_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__le_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = (x <= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__le_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij <= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB (_bind1st_tran__le_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__le_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_uint8_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint8_fc32) // op(A') function: GB (_unop_tran__identity_uint8_fc32) // C type: uint8_t // A type: GxB_FC32_t // cast: uint8_t cij = GB_cast_to_uint8_t ((double) crealf (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ uint8_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 = x ; // casting #define GB_CAST(z, aij) \ uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint8_fc32) ( uint8_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_uint8_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
declare-variant-3.c
void f1 (void); #pragma omp declare variant (f1) match (construct={target}) void f2 (void); void f3 (void); #pragma omp declare variant (f3) match (construct={teams}) void f4 (void); void f5 (void); #pragma omp declare variant (f5) match (construct={parallel}) void f6 (void); void f7 (void); #pragma omp declare variant (f7) match (construct={for}) void f8 (void); void f9 (void); #pragma omp declare variant (f9) match (construct={target,teams,parallel,for}) void f10 (void); void f11 (void); #pragma omp declare variant (f11) match (construct={teams,for,parallel}) void f12 (void); void f13 (void); #pragma omp declare variant (f13) match (device={kind(any)}) void f14 (void); #pragma omp declare variant (f13) match (device={kind("host")}) void f15 (void); #pragma omp declare variant (f13) match (device={kind(nohost)}) void f16 (void); #pragma omp declare variant (f13) match (device={kind(cpu)}) void f17 (void); #pragma omp declare variant (f13) match (device={kind("gpu")}) void f18 (void); #pragma omp declare variant (f13) match (device={kind(fpga)}) void f19 (void); #pragma omp declare variant (f13) match (device={kind(any,any)}) void f20 (void); #pragma omp declare variant (f13) match (device={kind(host,nohost)}) void f21 (void); #pragma omp declare variant (f13) match (device={kind("cpu","gpu","fpga")}) void f22 (void); #pragma omp declare variant (f13) match (device={kind(any,cpu,nohost)}) void f23 (void); #pragma omp declare variant (f13) match (device={isa(avx)}) void f24 (void); #pragma omp declare variant (f13) match (device={isa(sse4,"avx512f",avx512vl,avx512bw)}) void f25 (void); #pragma omp declare variant (f13) match (device={arch("x86_64")}) void f26 (void); #pragma omp declare variant (f13) match (device={arch(riscv64)}) void f27 (void); #pragma omp declare variant (f13) match (device={arch(nvptx)}) void f28 (void); #pragma omp declare variant (f13) match (device={arch(x86_64),isa("avx512f","avx512vl"),kind(cpu)}) void f29 (void); #pragma omp declare variant (f13) match (implementation={vendor(amd)}) void f30 (void); #pragma omp declare variant (f13) match (implementation={vendor(arm)}) void f31 (void); #pragma omp declare variant (f13) match (implementation={vendor("bsc")}) void f32 (void); #pragma omp declare variant (f13) match (implementation={vendor(cray)}) void f33 (void); #pragma omp declare variant (f13) match (implementation={vendor(fujitsu)}) void f34 (void); #pragma omp declare variant (f13) match (implementation={vendor(gnu)}) void f35 (void); #pragma omp declare variant (f13) match (implementation={vendor(ibm)}) void f36 (void); #pragma omp declare variant (f13) match (implementation={vendor("intel")}) void f37 (void); #pragma omp declare variant (f13) match (implementation={vendor(llvm)}) void f38 (void); #pragma omp declare variant (f13) match (implementation={vendor(pgi)}) void f39 (void); #pragma omp declare variant (f13) match (implementation={vendor(ti)}) void f40 (void); #pragma omp declare variant (f13) match (implementation={vendor(unknown)}) void f41 (void); #pragma omp declare variant (f13) match (implementation={vendor(gnu,llvm,intel,ibm)}) void f42 (void); #pragma omp declare variant (f13) match (implementation={extension(my_cute_extension)}) /* { dg-warning "unknown property 'my_cute_extension' of 'extension' selector" } */ void f43 (void); #pragma omp declare variant (f13) match (implementation={extension(some_other_ext,another_ext)}) /* { dg-warning "unknown property 'some_other_ext' of 'extension' selector" } */ void f44 (void); /* { dg-warning "unknown property 'another_ext' of 'extension' selector" "" { target *-*-* } .-1 } */ #pragma omp declare variant (f13) match (implementation={unified_shared_memory}) void f45 (void); #pragma omp declare variant (f13) match (implementation={unified_address}) void f46 (void); #pragma omp declare variant (f13) match (implementation={dynamic_allocators}) void f47 (void); #pragma omp declare variant (f13) match (implementation={reverse_offload}) void f48 (void); #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(seq_cst)}) void f49 (void); #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(relaxed)}) void f50 (void); #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(acq_rel)}) void f51 (void); #pragma omp declare variant (f14) match (implementation={atomic_default_mem_order(acq_rel),vendor(gnu),unified_address,extension(foobar)}) /* { dg-warning "unknown property 'foobar' of 'extension' selector" } */ void f52 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(3):amd)}) void f53 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(4):"arm")}) void f54 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(5):bsc)}) void f55 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(6):cray)}) void f56 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(7):fujitsu)}) void f57 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(8):gnu)}) void f58 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(9):ibm)}) void f59 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(10):intel)}) void f60 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(11):llvm)}) void f61 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(12):pgi)}) void f62 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(13):"ti")}) void f63 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(14):unknown)}) void f64 (void); #pragma omp declare variant (f13) match (implementation={vendor(score(15):gnu,llvm,intel,ibm)}) void f65 (void); #pragma omp declare variant (f13) match (implementation={extension(score(16):my_cute_extension)}) /* { dg-warning "unknown property 'my_cute_extension' of 'extension' selector" } */ void f66 (void); #pragma omp declare variant (f13) match (implementation={extension(score(17):some_other_ext,another_ext)}) /* { dg-warning "unknown property 'some_other_ext' of 'extension' selector" } */ void f67 (void); /* { dg-warning "unknown property 'another_ext' of 'extension' selector" "" { target *-*-* } .-1 } */ #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(score(18):seq_cst)}) void f68 (void); #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(score(19):relaxed)}) void f69 (void); #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(score(20):acq_rel)}) void f70 (void); #pragma omp declare variant (f13) match (implementation={atomic_default_mem_order(score(21):acq_rel),vendor(score(22):gnu),unified_address,extension(score(22):foobar)}) /* { dg-warning "unknown property 'foobar' of 'extension' selector" } */ void f71 (void); #pragma omp declare variant (f13) match (user={condition(0)}) void f72 (void); #pragma omp declare variant (f13) match (user={condition(272-272*1)}) void f73 (void); #pragma omp declare variant (f13) match (user={condition(score(25):1)}) void f74 (void); #pragma omp declare variant (f13) match (device={kind(any,"any")}) void f75 (void); #pragma omp declare variant (f13) match (device={kind("any","any")}) void f76 (void); #pragma omp declare variant (f13) match (device={kind("any",any)}) void f77 (void); #pragma omp declare variant (f13) match (implementation={vendor(nvidia)}) void f78 (void); #pragma omp declare variant (f13) match (user={condition(score(0):0)}) void f79 (void);
cpu_ctc.h
#pragma once #include <tuple> #include <cmath> #include <limits> #include <algorithm> #include <numeric> #if !defined(CTC_DISABLE_OMP) && !defined(APPLE) #include <omp.h> #endif #include "ctc_helper.h" template<typename ProbT> class CpuCTC { public: // Noncopyable CpuCTC(int alphabet_size, int minibatch, void* workspace, int num_threads) : alphabet_size_(alphabet_size), minibatch_(minibatch), num_threads_(num_threads), workspace_(workspace) { #if defined(CTC_DISABLE_OMP) || defined(APPLE) #else if (num_threads > 0) { omp_set_num_threads(num_threads); } else { num_threads_ = omp_get_max_threads(); } #endif }; CpuCTC(const CpuCTC&) = delete; CpuCTC& operator=(const CpuCTC&) = delete; ctcStatus_t cost_and_grad(const ProbT* const activations, ProbT *grads, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths); ctcStatus_t score_forward(const ProbT* const activations, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths); private: class CpuCTC_metadata { private: int setup_labels(const int* const labels, int L, int S); public: CpuCTC_metadata(int L, int S, int T, int mb, int alphabet_size, void* workspace, size_t bytes_used, const int* const labels); ProbT* alphas; ProbT* betas; int* labels_w_blanks; int* e_inc; int* s_inc; ProbT* output; int repeats; }; int alphabet_size_; // Number of characters plus blank int minibatch_; int num_threads_; void* workspace_; void softmax(const ProbT* const activations, ProbT* probs, const int* const input_lengths); std::tuple<ProbT, bool> cost_and_grad_kernel(ProbT *grad, const ProbT* const probs, const int* const labels, int T, int L, int mb, size_t bytes_used); ProbT compute_alphas(const ProbT* probs, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas); ProbT compute_betas_and_grad(ProbT* grad, const ProbT* const probs, ProbT log_partition, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas, ProbT* betas, ProbT* output); }; template<typename ProbT> CpuCTC<ProbT>::CpuCTC_metadata::CpuCTC_metadata(int L, int S, int T, int mb, int alphabet_size, void* workspace, size_t bytes_used, const int* const labels) { alphas = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * S * T; std::fill(alphas, alphas + S * T, ctc_helper::neg_inf<ProbT>()); betas = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * S; std::fill(betas, betas + S, ctc_helper::neg_inf<ProbT>()); labels_w_blanks = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; e_inc = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; s_inc = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; output = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * alphabet_size; repeats = setup_labels(labels, L, S); } template<typename ProbT> int CpuCTC<ProbT>::CpuCTC_metadata::setup_labels(const int* const labels, int L, int S) { int e_counter = 0; int s_counter = 0; s_inc[s_counter++] = 1; int repeats = 0; for (int i = 1; i < L; ++i) { if (labels[i-1] == labels[i]) { s_inc[s_counter++] = 1; s_inc[s_counter++] = 1; e_inc[e_counter++] = 1; e_inc[e_counter++] = 1; ++repeats; } else { s_inc[s_counter++] = 2; e_inc[e_counter++] = 2; } } e_inc[e_counter++] = 1; for (int i = 0; i < L; ++i) { labels_w_blanks[2 * i] = ctc_helper::BLANK; labels_w_blanks[2 * i + 1] = labels[i]; } labels_w_blanks[S - 1] = ctc_helper::BLANK; return repeats; } template<typename ProbT> void CpuCTC<ProbT>::softmax(const ProbT* const activations, ProbT* probs, const int* const input_lengths) { #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { for(int c = 0; c < input_lengths[mb]; ++c) { int col_offset = (mb + minibatch_ * c) * alphabet_size_; ProbT max_activation = -std::numeric_limits<ProbT>::infinity(); for(int r = 0; r < alphabet_size_; ++r) max_activation = std::max(max_activation, activations[r + col_offset]); ProbT denom = ProbT(0.); for(int r = 0; r < alphabet_size_; ++r) denom += std::exp(activations[r + col_offset] - max_activation); for(int r = 0; r < alphabet_size_; ++r) { probs[r + col_offset] = std::exp(activations[r + col_offset] - max_activation) / denom; } } } } template<typename ProbT> std::tuple<ProbT, bool> CpuCTC<ProbT>::cost_and_grad_kernel(ProbT *grad, const ProbT* const probs, const int* const labels, int T, int L, int mb, size_t bytes_used) { const int S = 2*L + 1; // Number of labels with blanks CpuCTC_metadata ctcm(L, S, T, mb, alphabet_size_, workspace_, bytes_used, labels); bool over_threshold = false; if (L + ctcm.repeats > T) { return std::make_tuple(ProbT(0), over_threshold); // TODO, not right to return 0 } ProbT llForward = compute_alphas(probs, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas); ProbT llBackward = compute_betas_and_grad(grad, probs, llForward, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas, ctcm.betas, ctcm.output); ProbT diff = std::abs(llForward - llBackward); if (diff > ctc_helper::threshold) { over_threshold = true; } return std::make_tuple(-llForward, over_threshold); } // Computes forward probabilities template<typename ProbT> ProbT CpuCTC<ProbT>::compute_alphas(const ProbT* probs, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas) { int start = (((S /2) + repeats - T) < 0) ? 0 : 1, end = S > 1 ? 2 : 1; for (int i = start; i < end; ++i) { alphas[i] = std::log(probs[labels[i]]); } for(int t = 1; t < T; ++t) { int remain = (S / 2) + repeats - (T - t); if(remain >= 0) start += s_inc[remain]; if(t <= (S / 2) + repeats) end += e_inc[t - 1]; int startloop = start; int idx1 = t * S, idx2 = (t - 1) * S, idx3 = t * (alphabet_size_ * minibatch_); if (start == 0) { alphas[idx1] = alphas[idx2] + std::log(probs[ctc_helper::BLANK + idx3]); startloop += 1; } for(int i = startloop; i < end; ++i) { ProbT prev_sum = ctc_helper::log_plus<ProbT>()(alphas[i + idx2], alphas[(i-1) + idx2]); // Skip two if not on blank and not on repeat. if (labels[i] != ctc_helper::BLANK && i != 1 && labels[i] != labels[i-2]) prev_sum = ctc_helper::log_plus<ProbT>()(prev_sum, alphas[(i-2) + idx2]); alphas[i + idx1] = prev_sum + std::log(probs[labels[i] + idx3]); } } ProbT loglike = ctc_helper::neg_inf<ProbT>(); for(int i = start; i < end; ++i) { loglike = ctc_helper::log_plus<ProbT>()(loglike, alphas[i + (T - 1) * S]); } return loglike; } // Starting from T, we sweep backward over the alpha array computing one column // of betas as we go. At each position we can update product alpha * beta and then // sum into the gradient associated with each label. // NOTE computes gradient w.r.t UNNORMALIZED final layer activations. // Assumed passed in grads are already zeroed! template<typename ProbT> ProbT CpuCTC<ProbT>::compute_betas_and_grad(ProbT* grad, const ProbT* const probs, ProbT log_partition, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas, ProbT* betas, ProbT* output) { int start = S > 1 ? (S - 2) : 0, end = (T > (S / 2) + repeats) ? S : S-1; std::fill(output, output + alphabet_size_, ctc_helper::neg_inf<ProbT>()); //set the starting values in the beta column at the very right edge for (int i = start; i < end; ++i) { betas[i] = std::log(probs[labels[i] + (T - 1) * (alphabet_size_ * minibatch_)]); //compute alpha * beta in log space at this position in (S, T) space alphas[i + (T - 1) * S] += betas[i]; //update the gradient associated with this label //essentially performing a reduce-by-key in a sequential manner output[labels[i]] = ctc_helper::log_plus<ProbT>()(alphas[i + (T - 1) * S], output[labels[i]]); } //update the gradient wrt to each unique label for (int i = 0; i < alphabet_size_; ++i) { int idx3 = (T - 1) * alphabet_size_ * minibatch_ + i; if (output[i] == 0.0 || output[i] == ctc_helper::neg_inf<ProbT>() || probs[idx3] == 0.0) { grad[idx3] = probs[idx3]; } else { grad[idx3] = probs[idx3] - std::exp(output[i] - std::log(probs[idx3]) - log_partition); } } //loop from the second to last column all the way to the left for(int t = T - 2; t >= 0; --t) { int remain = (S / 2) + repeats - (T - t); if(remain >= -1) start -= s_inc[remain + 1]; if(t < (S / 2) + repeats) end -= e_inc[t]; int endloop = end == S ? end - 1 : end; int idx1 = t * S, idx3 = t * (alphabet_size_ * minibatch_); std::fill(output, output + alphabet_size_, ctc_helper::neg_inf<ProbT>()); for(int i = start; i < endloop; ++i) { ProbT next_sum = ctc_helper::log_plus<ProbT>()(betas[i], betas[(i+1)]); // Skip two if not on blank and not on repeat. if (labels[i] != ctc_helper::BLANK && i != (S-2) && labels[i] != labels[i+2]){ next_sum = ctc_helper::log_plus<ProbT>()(next_sum, betas[(i+2)]); } betas[i] = next_sum + std::log(probs[labels[i] + idx3]); //compute alpha * beta in log space alphas[i + idx1] += betas[i]; //update the gradient associated with this label output[labels[i]] = ctc_helper::log_plus<ProbT>()(alphas[i + idx1], output[labels[i]]); } if (end == S) { betas[(S-1)] = betas[(S-1)] + std::log(probs[ctc_helper::BLANK + idx3]); alphas[(S-1) + idx1] += betas[(S-1)]; output[labels[S-1]] = ctc_helper::log_plus<ProbT>()(alphas[S-1 + idx1], output[labels[S-1]]); } //go over the unique labels and compute the final grad // wrt to each one at this time step for (int i = 0; i < alphabet_size_; ++i) { if (output[i] == 0.0 || output[i] == ctc_helper::neg_inf<ProbT>() || probs[idx3] == 0.0) { grad[idx3] = probs[idx3]; } else { grad[idx3] = probs[idx3] - std::exp(output[i] - std::log(probs[idx3]) - log_partition); } ++idx3; } } ProbT loglike = ctc_helper::neg_inf<ProbT>(); for(int i = start; i < end; ++i) { loglike = ctc_helper::log_plus<ProbT>()(loglike, betas[i]); } return loglike; } template<typename ProbT> ctcStatus_t CpuCTC<ProbT>::cost_and_grad(const ProbT* const activations, ProbT *grads, ProbT *costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths) { if (activations == nullptr || grads == nullptr || costs == nullptr || flat_labels == nullptr || label_lengths == nullptr || input_lengths == nullptr ) return CTC_STATUS_INVALID_VALUE; ProbT* probs = static_cast<ProbT *>(workspace_); int maxT = *std::max_element(input_lengths, input_lengths + minibatch_); size_t bytes_used = sizeof(ProbT) * minibatch_ * alphabet_size_ * maxT; //per minibatch memory size_t per_minibatch_bytes = 0; int maxL = *std::max_element(label_lengths, label_lengths + minibatch_);; int maxS = 2 * maxL + 1; //output per_minibatch_bytes += sizeof(float) * alphabet_size_; //alphas per_minibatch_bytes += sizeof(float) * maxS * maxT; //betas per_minibatch_bytes += sizeof(float) * maxS; //labels w/blanks, e_inc, s_inc per_minibatch_bytes += 3 * sizeof(int) * maxS; softmax(activations, probs, input_lengths); #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { const int T = input_lengths[mb]; // Length of utterance (time) const int L = label_lengths[mb]; // Number of labels in transcription bool mb_status; std::tie(costs[mb], mb_status) = cost_and_grad_kernel(grads + mb * alphabet_size_, probs + mb * alphabet_size_, flat_labels + std::accumulate(label_lengths, label_lengths + mb, 0), T, L, mb, bytes_used + mb * per_minibatch_bytes); } return CTC_STATUS_SUCCESS; } template<typename ProbT> ctcStatus_t CpuCTC<ProbT>::score_forward(const ProbT* const activations, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths) { if (activations == nullptr || costs == nullptr || flat_labels == nullptr || label_lengths == nullptr || input_lengths == nullptr ) return CTC_STATUS_INVALID_VALUE; ProbT* probs = static_cast<ProbT *>(workspace_); int maxT = *std::max_element(input_lengths, input_lengths + minibatch_); size_t bytes_used = sizeof(ProbT) * minibatch_ * alphabet_size_ * maxT; //per minibatch memory size_t per_minibatch_bytes = 0; int maxL = *std::max_element(label_lengths, label_lengths + minibatch_); int maxS = 2 * maxL + 1; //output per_minibatch_bytes += sizeof(float) * alphabet_size_; //alphas per_minibatch_bytes += sizeof(float) * maxS * maxT; //betas per_minibatch_bytes += sizeof(float) * maxS; //labels w/blanks, e_inc, s_inc per_minibatch_bytes += 3 * sizeof(int) * maxS; softmax(activations, probs, input_lengths); #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { const int T = input_lengths[mb]; // Length of utterance (time) const int L = label_lengths[mb]; // Number of labels in transcription const int S = 2*L + 1; // Number of labels with blanks CpuCTC_metadata ctcm(L, S, T, mb, alphabet_size_, workspace_, bytes_used + mb * per_minibatch_bytes, flat_labels + std::accumulate(label_lengths, label_lengths + mb, 0)); if (L + ctcm.repeats > T) costs[mb] = ProbT(0); else { costs[mb] = -compute_alphas(probs + mb * alphabet_size_, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas); } } return CTC_STATUS_SUCCESS; }
cg_aux.c
//MIT License // //Copyright (c) 2018 Sicong Zhuang // //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 "cg_aux.h" const char *scan_dconspec = "%lf"; const char *scan_sconspec = "%f"; void hb_read_double(char *input_file, int *m, int *n, int *elemc, int **vptr, int **vpos, double **vval) { double *exact = NULL; double *guess = NULL; int i; int indcrd; char *indfmt = NULL; FILE *input; int j; char *key = NULL; int khi; int klo; char *mxtype = NULL; int neltvl; int nrhs; int nrhsix; int ptrcrd; char *ptrfmt = NULL; int rhscrd; char *rhsfmt = NULL; int *rhsind = NULL; int *rhsptr = NULL; char *rhstyp = NULL; double *rhsval = NULL; double *rhsvec = NULL; char *title = NULL; int totcrd; int valcrd; char *valfmt = NULL; int nrow; int ncol; int nnzero; int *colptr = NULL; int *rowind = NULL; double *values = NULL; input = fopen ( input_file, "rt" ); if ( !input ) { printf ( " Error opening the file.\n" ); return; } hb_file_read ( input, &title, &key, &totcrd, &ptrcrd, &indcrd, &valcrd, &rhscrd, &mxtype, &nrow, &ncol, &nnzero, &neltvl, &ptrfmt, &indfmt, &valfmt, &rhsfmt, &rhstyp, &nrhs, &nrhsix, &colptr, &rowind, &values, &rhsval, &rhsptr, &rhsind, &rhsvec, &guess, &exact ); fclose ( input ); if ( exact ) { free ( exact ); } if ( guess ) { free ( guess ); } if ( rhsind ) { free ( rhsind ); } if ( rhsptr ) { free ( rhsptr ); } if ( rhsval ) { free ( rhsval ); } if ( rhsvec ) { free ( rhsvec ); } *m = nrow; *n = ncol; *elemc = nnzero; *vptr = colptr; *vpos = rowind; *vval = values; return; } void hb_reset(hbmat_t *A) { A->m = 0; A->n =0; A->elemc = 0; A->vptr = 0; A->vpos = 0; A->vval = 0; A->vdiag = NULL; A->b = 0; A->trans = 0; A->orig = 0; A->hyper = 0; A->orig_row = 0; A->orig_col = 0; A->e_tree = 0; A->type = 0; A->FACT = 0; } void one2zero(hbmat_t* in_matrix) { int m = in_matrix->m; int elemc = in_matrix->elemc; int *vptr = in_matrix->vptr; int *vpos = in_matrix->vpos; int i; for ( i = 0; i <= m; i++ ) { vptr[i]--; } for ( i=0; i<elemc; i++ ) { vpos[i]--; } } typedef struct _sparse_nodes { int row; int col; double val; struct sparse_node *next; struct sparse_node *current; } _sn_t; /* Expand an symmetric half matrix B to its full counterpart A */ void hb_sym_expand(hbmat_t *A, hbmat_t *B) { hb_init_basic(A, B); int m = A->m; A->elemc = B->elemc * 2 - m; int nnz = A->elemc; A->vptr = malloc((m+1) * sizeof(int)); A->vpos = malloc(nnz * sizeof(int)); A->vval = malloc(nnz * sizeof(double)); int *vptra = A->vptr; int *vposa = A->vpos; double *vvala = A->vval; int *vptrb = B->vptr; int *vposb = B->vpos; double *vvalb = B->vval; _sn_t *ll_mat = malloc(m * sizeof(_sn_t)); int i; for ( i = 0; i < m; i++ ) { ll_mat[i].row = m; ll_mat[i].col = -1; ll_mat[i].val = 0.0; ll_mat[i].next = NULL; ll_mat[i].current = &ll_mat[i]; } int vptr_c = 0; int elemc_c = 0; for ( i = 0; i < m; i++ ) { vptra[i] = vptr_c; int bptr = vptrb[i]; int eptr = vptrb[i+1]; /* Fill the lower csr info */ _sn_t *c = &ll_mat[i]; while ( c != NULL && c->col != -1 ) { vposa[elemc_c] = c->col; vvala[elemc_c] = c->val; elemc_c++; vptr_c++; c = c->next; } /* Copy the upper csr info */ int j; for ( j = bptr; j < eptr; j++ ) { int col = vposb[j]; double val = vvalb[j]; vposa[elemc_c] = col; vvala[elemc_c] = val; elemc_c++; /*-------------------------------------------------* * linked list insert *-------------------------------------------------*/ _sn_t *head = &ll_mat[col]; _sn_t *current = ll_mat[col].current; if ( current->col != -1 ) { current->next = malloc(sizeof(_sn_t)); current = current->next; head->current = current; } current->row = col; current->col = i; current->val = val; current->next = NULL; current->current = current; /*-------------------------------------------------* * linked list insert end *-------------------------------------------------*/ } vptr_c += eptr - bptr; } vptra[m] = vptr_c; for ( i = 0; i < m; i++ ) { _sn_t *c= ll_mat[i].next; while ( c != NULL ) { _sn_t *n = c->next; free(c); c = n; } } free(ll_mat); } /* Copy basic info from B to A */ void hb_init_basic(hbmat_t *A, hbmat_t *B) { hb_reset(A); int M = B->m; int elemc = B->elemc; A->m = A->n = M; A->elemc = elemc; } void hb_free(hbmat_t *A) { free(A->vptr); free(A->vpos); free(A->vval); free(A->vdiag); free(A->e_tree); free(A); } void* __hb2hbh_block(int I, int J, hbmat_t *A, int b, hbmat_t *Bp) { int alloc = Bp == NULL; if ( b < 0 ) { fprintf(stderr, "err: b must be positive\n"); return NULL; } int m = A->m; int n = A->n; int* vptr = A->vptr; int* vpos = A->vpos; double* vval = A->vval; int offs = vptr[0] == 0 ? 0 : 1; int csr = 1;//hb_CSR(A); int brow = I*b; int bcol = J*b; int rleft = m - brow; int cleft = n - bcol; int rows = b > rleft ? rleft : b; int cols = b > cleft ? cleft : b; int erow = brow + rows; int ecol = bcol + cols; int dimb = csr ? brow : bcol; int dime = csr ? erow : ecol; int rngb = csr ? bcol : brow; int rnge = csr ? ecol : erow; vector_t* ab_vptr = vector_create(); vector_t* ab_vpos = vector_create(); vector_t* ab_vval = vector_create(); vel_t vel; int L; for ( L = dimb; L < dime; ++L ) { vel.i = ab_vpos->elemc + offs; vector_insert(ab_vptr, vel); int k; for ( k = vptr[L]; k < vptr[L+1]; ++k ) { int lk = k - offs; int c = vpos[lk] - offs; if ( c >= rngb && c < rnge ) { vel.i = c - rngb + offs; vector_insert(ab_vpos, vel); vel.d = vval[lk]; vector_insert(ab_vval, vel); } } } vel.i = ab_vpos->elemc + offs; vector_insert(ab_vptr, vel); if ( alloc ) { Bp = malloc(sizeof(hbmat_t)); hb_reset(Bp); } if ( ab_vpos->elemc ) { Bp->m = rows; Bp->n = cols; Bp->elemc = ab_vpos->elemc; Bp->vdiag = NULL; Bp->vptr = vector2int(ab_vptr); Bp->vpos = vector2int(ab_vpos); Bp->vval = vector2double(ab_vval); } else { vector_free(ab_vptr); vector_free(ab_vpos); vector_free(ab_vval); return NULL; } return Bp; } hbmat_t* hb2hbh(hbmat_t *A, int b, int is_csr) { int m = A->m; int n = A->n; int elemc = A->elemc; int *vptr = A->vptr; int *vpos = A->vpos; double* vval = A->vval; int M = (m+b-1) / b; int N = (n+b-1) / b; int num = M * N; int offs = vptr[0] == 0 ? 0 : 1; hbmat_t* hyper = malloc(sizeof(hbmat_t)); hb_reset(hyper); hyper->m = M; hyper->n = N; hyper->vdiag = NULL; hyper->orig = A; hyper->vval = malloc(num * sizeof(hbmat_t*)); hbmat_t** hbmat_array = malloc(num * sizeof(hbmat_t*)); vector_t* ab_vptr = vector_create(); vector_t* ab_vpos = vector_create(); vel_t pos_val; int acc0 = 0; int acc = 0; int I, J; if ( is_csr ) { for ( I = 0; I < M; ++I ) { pos_val.i = ab_vpos->elemc + offs; vector_insert(ab_vptr, pos_val); for ( J = 0; J < N; ++J ) { hbmat_t *B = __hb2hbh_block(I, J, A, b, NULL); if ( B != NULL ) { pos_val.i = J + offs; vector_insert(ab_vpos, pos_val); ((hbmat_t**)hyper->vval)[acc0] = B; ++acc0; } ++acc; } } } else { printf("warn: hb2hbh for csc not yet implemented\n"); } pos_val.i = ab_vpos->elemc + offs; vector_insert(ab_vptr, pos_val); hyper->elemc = ab_vpos->elemc; hyper->vptr = vector2int(ab_vptr); hyper->vpos = vector2int(ab_vpos); // hb_setdiag(hyper); return hyper; } /* Construct an array of block diagonal submatrices */ void hb_sym_diag_block(hbmat_t *src_mat, int bsze, hbmat_t *diagb) { /* Assuming CSR */ int m = src_mat->m; /* Number of subblocks */ int bs = (m+bsze-1)/bsze; int *svptr = src_mat->vptr; int *svpos = src_mat->vpos; double *svval = src_mat->vval; int i; /* Loop for generating all the diagonal blocks*/ for ( i = 0; i < bs; i++ ) { hbmat_t *d = &diagb[i]; int elemc = 0; int brow = i*bsze; int erow = brow+bsze; erow = erow > m ? m : erow; int dim = erow - brow; d->m = d->n = dim; // Allocate individual HB structures // Note that vpos and vval size are over-estimated int *vptr = malloc((dim+1) * sizeof(int)); int esze = (svptr[erow] - svptr[brow]); int *vpos = malloc(esze * sizeof(int)); double *vval = malloc(esze * sizeof(double)); int idx; int row; /* Traverse through rows */ for ( row = brow, idx = 0; row < erow; row++ ,idx++) { vptr[idx] = elemc; int pos = svptr[row]; int epos = svptr[row+1]; while ( pos < epos ) { int col = svpos[pos]; /* Only take the lower triangular part of the matrix */ // if ( col >= row && col < erow ) { //Upper // if ( col >= brow && col < row ) { //Lower if ( col >= brow && col < erow ) { //Complete vpos[elemc] = col - brow; vval[elemc] = svval[pos]; elemc++; } pos++; } } vptr[idx] = elemc; d->elemc = elemc; d->vptr = vptr; //FIXME using realloc to reduce memory consumption d->vpos = vpos; d->vval = vval; //TODO Remove verifications // hb_sanity_check("A_hb", d, 0); // assert(idx == dim); // assert(d->vptr != NULL && d->vpos != NULL && d->vval != NULL); } } /* Block diagonal (non-split) */ void hb_sym_diag(hbmat_t *src_mat, int bsze, hbmat_t *d) { /* Assuming CSR */ int m = src_mat->m; int bs = (m+bsze-1)/bsze; int *svptr = src_mat->vptr; int *svpos = src_mat->vpos; double *svval = src_mat->vval; d->m = d->n = m; int elemc = d->elemc = 0; d->vptr = malloc((m+1) * sizeof(int)); d->vpos = malloc(src_mat->elemc * sizeof(int)); d->vval = malloc(src_mat->elemc * sizeof(double)); int *dvptr = d->vptr; int *dvpos = d->vpos; double *dvval = d->vval; int idx = 0; int i; for ( i = 0; i < bs; i++ ) { int brow = i*bsze; int erow = brow+bsze; erow = erow > m ? m : erow; int dim = erow - brow; // int esze = (svptr[erow] - svptr[brow]); // int idx; int row; /* Traverse through rows */ for ( row = brow; row < erow; row++) { dvptr[idx] = elemc; idx += 1; int pos = svptr[row]; int epos = svptr[row+1]; while ( pos < epos ) { int col = svpos[pos]; /* Only take the lower triangular part of the matrix */ // if ( col >= row && col < erow ) { //Upper // if ( col >= brow && col < row ) { //Lower if ( col >= brow && col < erow ) { //Complete //TODO Verify // vpos[elemc] = col - brow; dvpos[elemc] = col; dvval[elemc] = svval[pos]; elemc++; } pos++; } } dvptr[idx] = elemc; d->elemc = elemc; d->vptr = dvptr; d->vpos = dvpos; d->vval = dvval; } // printf("m %d n %d elemc : %d\n", d->m, d->n, d->elemc); // for(int i = 0; i < m; i++ ){ // printf("[%d]: %d ", i, dvptr[i]); // } // printf("\n\n"); // for(int i = 0; i < elemc; i++ ){ // printf("[%d]: %d ", i, dvpos[i]); // } // printf("\n\n"); // for(int i = 0; i < elemc; i++ ){ // printf("[%d]: %E ", i, dvval[i]); // } // printf("\n\n"); } int read_mm2dense(FILE *f, int m, int n, double *A) { char buf[1024]; double el; int i = 0; while ( fgets(buf, sizeof(buf), f) != NULL && i < m) { if ( buf[0] != '#' ) { sscanf(buf, FP_SCANSPEC, &el); *A++ = el; ++i; } } return 0; } // column-major void print_dense2mm(FILE *f, const char *name, int m, int n, const double *A, int lda) { printf("warning: writing obj %s\n", name); fprintf(f, "# name: %s\n", name); fprintf(f, "# type: matrix\n"); fprintf(f, "# rows: %i\n", m); fprintf(f, "# columns: %i\n", n); int i; for ( i=0; i<m; ++i ) { int j; for ( j=0; j<n; ++j ) { fprintf(f, "%.16e \n", A[j*lda+i]); // fprintf(f, "\n"); } // fprintf(f, "\n"); } } void fprint_dense2mm(const char *fname, const char *name, int m, int n, const double *A, int lda) { FILE *f = fopen(fname, "w"); if ( f == NULL ) { fprintf(stderr, "err: cannot open %s for writing\n", fname); } print_dense2mm(f, name, m, n, A, lda); fclose(f); } /* * BLAS/LAPACK task wrappers * */ void __t_copy(int p, int bm, int bn, int m, int n, double *x, double *y, int initx, int inity) { double *X = &x[initx]; double *Y = &y[inity]; int i_one = 1; int j; for ( j=0; j<bn; ++j ) { BLAS_cp(bm, &X[j*m], i_one, &Y[j*m], i_one); } } void __t_dot(int p, int bm, int bn, int m, int n, double *x, double *y, int initx, int inity, double *result) { double *X = &x[initx]; double *Y = &y[inity]; int i_one = 1; double local_result[bn]; double fp_one = 1.0; int j; for ( j=0; j<bn; ++j ) { local_result[j] = BLAS_dot(bm, X, i_one, Y, i_one); X += m; Y += m; } #pragma omp critical { BLAS_axpy(bn, fp_one, local_result, i_one, result, i_one); } } void __t_dot_array(int p, int bm, int bn, int m, int n, double *x, double *y, int initx, int inity, double *result, int initr) { double *X = &x[initx]; double *Y = &y[inity]; int i_one = 1; double local_result[bn]; double fp_one = 1.0; int j; for ( j=0; j<bn; ++j ) { result[initr+j] = BLAS_dot(bm, X, i_one, Y, i_one); X += m; Y += m; } } void _cg_dot2_array(int p, int bm, int bn, int m, int n, double *x, double *y, int initx, int inity, double *result, int initr, double *a, double *b, int inita, int initb, double *result2, int initr2) { double *X = &x[initx]; double *Y = &y[inity]; double *A = &a[inita]; double *B = &b[initb]; //double fp_one = 1.0; int i_one = 1; for ( int j=0; j<bn; ++j ) { result[initr+j] = BLAS_dot(bm, X, i_one, Y, i_one); X += m; Y += m; } int j; for ( int j=0; j<bn; ++j ) { result2[initr2+j] = BLAS_dot(bm, A, i_one, B, i_one); A += m; B += m; } } void _cg_dot2(int p, int bm, int bn, int m, int n, double *x, double *y, int initx, int inity, double *result, double *a, double *b, int inita, int initb, double *result2) { double *X = &x[initx]; double *Y = &y[inity]; double *A = &a[inita]; double *B = &b[initb]; double fp_one = 1.0; int i_one = 1; double local_result[bn]; for ( int j=0; j<bn; ++j ) { local_result[j] = BLAS_dot(bm, X, i_one, Y, i_one); X += m; Y += m; } double local_result2[bn]; int j; for ( int j=0; j<bn; ++j ) { local_result2[j] = BLAS_dot(bm, A, i_one, B, i_one); A += m; B += m; } #pragma omp critical { BLAS_axpy(bn, fp_one, local_result, i_one, result, i_one); BLAS_axpy(bn, fp_one, local_result2, i_one, result2, i_one); } } void __t_cpaxpy_comb(int bm, int bn, int m, int n, double alpha, double *Anum, double *Aden, double *X1, double *X2, double *Y1, double *Y2, double *Z1, double *Z2) { int i_one = 1; int j; for ( j=0; j<bn; ++j) { /* update of x */ double factor = Anum[j] / Aden[j]; BLAS_cp(bm, Y2, i_one, Z2, i_one); BLAS_axpy(bm, factor, X2, i_one, Z2, i_one); X2 += m; Y2 += m; Z2 += m; /* update of r */ factor = alpha * factor; BLAS_cp(bm, Y1, i_one, Z1, i_one); BLAS_axpy(bm, factor, X1, i_one, Z1, i_one); X1 += m; Y1 += m; Z1 += m; } } void __t_extm_axpy(int bm, int bn, int m, int n, double *SAnum, double *SAden, double *X, double *Y, double *Z, int p) { int i_one = 1; int j; for ( j=0; j<bn; ++j) { double f = SAnum[j] / SAden[j]; BLAS_cp(bm, &Y[j*m], i_one, &Z[j*m], i_one); BLAS_axpy(bm, f, &X[j*m], i_one, &Z[j*m], i_one); } } /* Non-optimal implementation of the mkl_csrmv when it is not present */ void manual_csrmv(char *trans, int m, int n, double alpha, double *avval, int *avpos, int *avptr, double *Bptr, double beta, double *Cptr) { if ( strcmp(trans, "N") || strcmp(trans, "n") ) { for ( int i = 0; i < m; i++ ) { double c = Cptr[i]; c = beta * c; for ( int v = avptr[i]; v < avptr[i+1]; v++ ) { int pos = avpos[v]; double val = avval[v]; c += alpha * val * Bptr[pos]; } Cptr[i] = c; } } else if ( strcmp(trans, "T") || strcmp(trans, "t") ) { int count = 0; for ( int i = 0; i < n; i++, count++ ) { for ( int v = avptr[i]; v < avptr[i+1]; v++ ) { int pos = avpos[v]; double val = avval[v]; if ( ! count ) { Cptr[pos] = alpha * val * Bptr[i] + beta * Cptr[pos]; } else { Cptr[pos] += alpha * val * Bptr[i]; } } } } }
convolution_3x3_pack8to4_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch, const Option& opt) { #if NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ if (ncnn::cpu_support_x86_avx512_vnni()) { extern void conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse_avx512vnni(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch, const Option& opt); conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse_avx512vnni(kernel, kernel_tm_pack8, inch, outch, opt); return; } #endif #if NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ if (ncnn::cpu_support_x86_avx_vnni()) { extern void conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse_avxvnni(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch, const Option& opt); conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse_avxvnni(kernel, kernel_tm_pack8, inch, outch, opt); return; } #endif #if NCNN_XOP && __SSE2__ && !__XOP__ if (ncnn::cpu_support_x86_xop()) { extern void conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse_xop(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch, const Option& opt); conv3x3s1_winograd42_transform_kernel_pack8to4_int8_sse_xop(kernel, kernel_tm_pack8, inch, outch, opt); return; } #endif // winograd42 transform kernel Mat kernel_tm(6 * 6, inch, outch, (size_t)2u); const short ktm[6][3] = { {6, 0, 0}, {-4, -4, -4}, {-4, 4, -4}, {1, 2, 4}, {1, -2, 4}, {0, 0, 6} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const signed char* kernel0 = (const signed char*)kernel + p * inch * 9 + q * 9; short* kernel_tm0 = kernel_tm.channel(p).row<short>(q); // transform kernel const signed char* k0 = kernel0; const signed char* k1 = kernel0 + 3; const signed char* k2 = kernel0 + 6; // h short tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { short* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 36-inch-outch // dst = 4b-8a-inch/8a-36-outch/4b kernel_tm_pack8.create(inch / 8, 36, outch / 4, (size_t)2u * 32, 32); int q = 0; for (; q + 3 < outch; q += 4) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); Mat kernel_tm = kernel_tm_pack8.channel(q / 4); for (int k = 0; k < 36; k++) { short* g00 = kernel_tm.row<short>(k); for (int p = 0; p + 7 < inch; p += 8) { #if __AVXVNNI__ || __AVX512VNNI__ || __XOP__ for (int i = 0; i < 4; i++) { const short* k00 = k0.row<const short>(p + i * 2); const short* k10 = k1.row<const short>(p + i * 2); const short* k20 = k2.row<const short>(p + i * 2); const short* k30 = k3.row<const short>(p + i * 2); const short* k01 = k0.row<const short>(p + i * 2 + 1); const short* k11 = k1.row<const short>(p + i * 2 + 1); const short* k21 = k2.row<const short>(p + i * 2 + 1); const short* k31 = k3.row<const short>(p + i * 2 + 1); g00[0] = k00[k]; g00[1] = k01[k]; g00[2] = k10[k]; g00[3] = k11[k]; g00[4] = k20[k]; g00[5] = k21[k]; g00[6] = k30[k]; g00[7] = k31[k]; g00 += 8; } #else for (int i = 0; i < 8; i++) { const short* k00 = k0.row<const short>(p + i); const short* k10 = k1.row<const short>(p + i); const short* k20 = k2.row<const short>(p + i); const short* k30 = k3.row<const short>(p + i); g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00 += 4; } #endif } } } } static void conv3x3s1_winograd42_pack8to4_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt) { #if NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ if (ncnn::cpu_support_x86_avx512_vnni()) { extern void conv3x3s1_winograd42_pack8to4_int8_sse_avx512vnni(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); conv3x3s1_winograd42_pack8to4_int8_sse_avx512vnni(bottom_blob, top_blob, kernel_tm, opt); return; } #endif #if NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ if (ncnn::cpu_support_x86_avx_vnni()) { extern void conv3x3s1_winograd42_pack8to4_int8_sse_avxvnni(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); conv3x3s1_winograd42_pack8to4_int8_sse_avxvnni(bottom_blob, top_blob, kernel_tm, opt); return; } #endif #if NCNN_XOP && __SSE2__ && !__XOP__ if (ncnn::cpu_support_x86_xop()) { extern void conv3x3s1_winograd42_pack8to4_int8_sse_xop(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); conv3x3s1_winograd42_pack8to4_int8_sse_xop(bottom_blob, top_blob, kernel_tm, opt); return; } #endif int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; // size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; bottom_blob_tm.create(tiles, 36, inch, 2u * elempack, elempack, opt.workspace_allocator); // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r04 + r03 // 2 = 4 * (r01 - r02) + r04 - r03 // 3 = -2 * (r01 - r03) + r04 - r02 // 4 = 2 * (r01 - r03) + r04 - r02 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); short tmp[6][6][8]; // tile for (int i = 0; i < h_tm / 6; i++) { for (int j = 0; j < w_tm / 6; j++) { const signed char* r0 = img0.row<const signed char>(i * 4) + (j * 4) * 8; for (int m = 0; m < 6; m++) { // TODO use _mm_cvtepi8_epi16 on sse4.1 __m128i _r00_01 = _mm_loadu_si128((const __m128i*)r0); __m128i _r02_03 = _mm_loadu_si128((const __m128i*)(r0 + 16)); __m128i _r04_05 = _mm_loadu_si128((const __m128i*)(r0 + 32)); __m128i _extr0001 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r00_01); __m128i _extr0203 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r02_03); __m128i _extr0405 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r04_05); __m128i _r00 = _mm_unpacklo_epi8(_r00_01, _extr0001); __m128i _r01 = _mm_unpackhi_epi8(_r00_01, _extr0001); __m128i _r02 = _mm_unpacklo_epi8(_r02_03, _extr0203); __m128i _r03 = _mm_unpackhi_epi8(_r02_03, _extr0203); __m128i _r04 = _mm_unpacklo_epi8(_r04_05, _extr0405); __m128i _r05 = _mm_unpackhi_epi8(_r04_05, _extr0405); __m128i _v5 = _mm_set1_epi16(5); __m128i _tmp0m = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_r00, 2), _r04), _mm_mullo_epi16(_r02, _v5)); __m128i _tmp1m = _mm_sub_epi16(_mm_add_epi16(_r04, _r03), _mm_slli_epi16(_mm_add_epi16(_r01, _r02), 2)); __m128i _tmp2m = _mm_add_epi16(_mm_sub_epi16(_r04, _r03), _mm_slli_epi16(_mm_sub_epi16(_r01, _r02), 2)); __m128i _tmp3m = _mm_sub_epi16(_mm_sub_epi16(_r04, _r02), _mm_slli_epi16(_mm_sub_epi16(_r01, _r03), 1)); __m128i _tmp4m = _mm_add_epi16(_mm_sub_epi16(_r04, _r02), _mm_slli_epi16(_mm_sub_epi16(_r01, _r03), 1)); __m128i _tmp5m = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_r01, 2), _r05), _mm_mullo_epi16(_r03, _v5)); _mm_storeu_si128((__m128i*)tmp[0][m], _tmp0m); _mm_storeu_si128((__m128i*)tmp[1][m], _tmp1m); _mm_storeu_si128((__m128i*)tmp[2][m], _tmp2m); _mm_storeu_si128((__m128i*)tmp[3][m], _tmp3m); _mm_storeu_si128((__m128i*)tmp[4][m], _tmp4m); _mm_storeu_si128((__m128i*)tmp[5][m], _tmp5m); r0 += w * 8; } short* r0_tm_0 = (short*)img0_tm + (i * w_tm / 6 + j) * 8; short* r0_tm_1 = r0_tm_0 + tiles * 8; short* r0_tm_2 = r0_tm_0 + tiles * 16; short* r0_tm_3 = r0_tm_0 + tiles * 24; short* r0_tm_4 = r0_tm_0 + tiles * 32; short* r0_tm_5 = r0_tm_0 + tiles * 40; for (int m = 0; m < 6; m++) { __m128i _tmp00 = _mm_loadu_si128((const __m128i*)tmp[m][0]); __m128i _tmp01 = _mm_loadu_si128((const __m128i*)tmp[m][1]); __m128i _tmp02 = _mm_loadu_si128((const __m128i*)tmp[m][2]); __m128i _tmp03 = _mm_loadu_si128((const __m128i*)tmp[m][3]); __m128i _tmp04 = _mm_loadu_si128((const __m128i*)tmp[m][4]); __m128i _tmp05 = _mm_loadu_si128((const __m128i*)tmp[m][5]); __m128i _v5 = _mm_set1_epi16(5); __m128i _r0tm0 = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_tmp00, 2), _tmp04), _mm_mullo_epi16(_tmp02, _v5)); __m128i _r0tm1 = _mm_sub_epi16(_mm_add_epi16(_tmp04, _tmp03), _mm_slli_epi16(_mm_add_epi16(_tmp01, _tmp02), 2)); __m128i _r0tm2 = _mm_add_epi16(_mm_sub_epi16(_tmp04, _tmp03), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp02), 2)); __m128i _r0tm3 = _mm_sub_epi16(_mm_sub_epi16(_tmp04, _tmp02), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp03), 1)); __m128i _r0tm4 = _mm_add_epi16(_mm_sub_epi16(_tmp04, _tmp02), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp03), 1)); __m128i _r0tm5 = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_tmp01, 2), _tmp05), _mm_mullo_epi16(_tmp03, _v5)); _mm_storeu_si128((__m128i*)r0_tm_0, _r0tm0); _mm_storeu_si128((__m128i*)r0_tm_1, _r0tm1); _mm_storeu_si128((__m128i*)r0_tm_2, _r0tm2); _mm_storeu_si128((__m128i*)r0_tm_3, _r0tm3); _mm_storeu_si128((__m128i*)r0_tm_4, _r0tm4); _mm_storeu_si128((__m128i*)r0_tm_5, _r0tm5); r0_tm_0 += tiles * 48; r0_tm_1 += tiles * 48; r0_tm_2 += tiles * 48; r0_tm_3 += tiles * 48; r0_tm_4 += tiles * 48; r0_tm_5 += tiles * 48; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = h_tm / 6 * w_tm / 6; // permute // bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; #if __AVX2__ if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator); #else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 36; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __AVX2__ for (; i + 3 < tiles; i += 4) { short* tmpptr = tm2.row<short>(i / 4); const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m256i _r0 = _mm256_loadu_si256((const __m256i*)r0); __m256i _r1 = _mm256_loadu_si256((const __m256i*)(r0 + 16)); _mm256_storeu_si256((__m256i*)tmpptr, _r0); _mm256_storeu_si256((__m256i*)(tmpptr + 16), _r1); r0 += bottom_blob_tm.cstep * 8; tmpptr += 32; } } #endif for (; i + 1 < tiles; i += 2) { #if __AVX2__ short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2); #else short* tmpptr = tm2.row<short>(i / 2); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m128i _r0 = _mm_loadu_si128((const __m128i*)r0); __m128i _r1 = _mm_loadu_si128((const __m128i*)(r0 + 8)); _mm_storeu_si128((__m128i*)tmpptr, _r0); _mm_storeu_si128((__m128i*)(tmpptr + 8), _r1); r0 += bottom_blob_tm.cstep * 8; tmpptr += 16; } } for (; i < tiles; i++) { #if __AVX2__ short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2 + i % 2); #else short* tmpptr = tm2.row<short>(i / 2 + i % 2); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m128i _r0 = _mm_loadu_si128((const __m128i*)r0); _mm_storeu_si128((__m128i*)tmpptr, _r0); r0 += bottom_blob_tm.cstep * 8; tmpptr += 8; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, 4u * 4, 4, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { int* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __AVX2__ for (; i + 3 < tiles; i += 4) { const short* r0 = bb2.row<const short>(i / 4); const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 __m256i _sum0_1 = _mm256_setzero_si256(); __m256i _sum2_3 = _mm256_setzero_si256(); __m256i _sum4_5 = _mm256_setzero_si256(); __m256i _sum6_7 = _mm256_setzero_si256(); for (int j = 0; j < nn; j++) { // 0 1 2 3 4 5 6 7 8 9 a b c d e f __m256i _val0 = _mm256_loadu_si256((const __m256i*)r0); __m256i _w01 = _mm256_loadu_si256((const __m256i*)k0); __m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ __m256i _val0_0123 = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0)); __m256i _val0_4567 = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2)); __m256i _val0_89ab = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4)); __m256i _val0_cdef = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6)); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val0_0123); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w01, _val0_89ab); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val0_4567); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w23, _val0_cdef); #else // 0 0 1 1 2 2 3 3 8 8 9 9 a a b b // 4 4 5 5 6 6 7 7 c c d d e e f f __m256i _val0_0123_89ab = _mm256_unpacklo_epi16(_val0, _val0); __m256i _val0_4567_cdef = _mm256_unpackhi_epi16(_val0, _val0); __m256i _val0_0123 = _mm256_permutevar8x32_epi32(_val0_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val0_4567 = _mm256_permutevar8x32_epi32(_val0_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val0_89ab = _mm256_permutevar8x32_epi32(_val0_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _val0_cdef = _mm256_permutevar8x32_epi32(_val0_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val0_0123); __m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val0_0123); __m256i _sl10_11 = _mm256_mullo_epi16(_w01, _val0_89ab); __m256i _sh10_11 = _mm256_mulhi_epi16(_w01, _val0_89ab); __m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val0_4567); __m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val0_4567); __m256i _sl12_13 = _mm256_mullo_epi16(_w23, _val0_cdef); __m256i _sh12_13 = _mm256_mulhi_epi16(_w23, _val0_cdef); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl12_13, _sh12_13)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl12_13, _sh12_13)); #endif __m256i _val1 = _mm256_loadu_si256((const __m256i*)(r0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ __m256i _val1_0123 = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0)); __m256i _val1_4567 = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2)); __m256i _val1_89ab = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4)); __m256i _val1_cdef = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6)); _sum4_5 = _mm256_dpwssd_epi32(_sum4_5, _w01, _val1_0123); _sum6_7 = _mm256_dpwssd_epi32(_sum6_7, _w01, _val1_89ab); _sum4_5 = _mm256_dpwssd_epi32(_sum4_5, _w23, _val1_4567); _sum6_7 = _mm256_dpwssd_epi32(_sum6_7, _w23, _val1_cdef); #else __m256i _val1_0123_89ab = _mm256_unpacklo_epi16(_val1, _val1); __m256i _val1_4567_cdef = _mm256_unpackhi_epi16(_val1, _val1); __m256i _val1_0123 = _mm256_permutevar8x32_epi32(_val1_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val1_4567 = _mm256_permutevar8x32_epi32(_val1_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val1_89ab = _mm256_permutevar8x32_epi32(_val1_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _val1_cdef = _mm256_permutevar8x32_epi32(_val1_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _sl04_05 = _mm256_mullo_epi16(_w01, _val1_0123); __m256i _sh04_05 = _mm256_mulhi_epi16(_w01, _val1_0123); __m256i _sl14_15 = _mm256_mullo_epi16(_w01, _val1_89ab); __m256i _sh14_15 = _mm256_mulhi_epi16(_w01, _val1_89ab); __m256i _sl06_07 = _mm256_mullo_epi16(_w23, _val1_4567); __m256i _sh06_07 = _mm256_mulhi_epi16(_w23, _val1_4567); __m256i _sl16_17 = _mm256_mullo_epi16(_w23, _val1_cdef); __m256i _sh16_17 = _mm256_mulhi_epi16(_w23, _val1_cdef); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpacklo_epi16(_sl04_05, _sh04_05)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpacklo_epi16(_sl14_15, _sh14_15)); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpacklo_epi16(_sl06_07, _sh06_07)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpacklo_epi16(_sl16_17, _sh16_17)); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpackhi_epi16(_sl04_05, _sh04_05)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpackhi_epi16(_sl14_15, _sh14_15)); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpackhi_epi16(_sl06_07, _sh06_07)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpackhi_epi16(_sl16_17, _sh16_17)); #endif r0 += 32; k0 += 32; } __m256i _sum0_2 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 2, 0, 0)); __m256i _sum1_3 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 3, 0, 1)); _sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3); __m256i _sum4_6 = _mm256_permute2x128_si256(_sum4_5, _sum6_7, _MM_SHUFFLE(0, 2, 0, 0)); __m256i _sum5_7 = _mm256_permute2x128_si256(_sum4_5, _sum6_7, _MM_SHUFFLE(0, 3, 0, 1)); _sum4_6 = _mm256_add_epi32(_sum4_6, _sum5_7); _mm256_storeu_si256((__m256i*)output0_tm, _sum0_2); _mm256_storeu_si256((__m256i*)(output0_tm + 8), _sum4_6); output0_tm += 16; } #endif for (; i + 1 < tiles; i += 2) { #if __AVX2__ const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2); #else const short* r0 = bb2.row<const short>(i / 2); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 #if __AVX2__ __m256i _sum0_1 = _mm256_setzero_si256(); __m256i _sum2_3 = _mm256_setzero_si256(); #else __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); #endif for (int j = 0; j < nn; j++) { #if __AVX2__ // 0 1 2 3 4 5 6 7 8 9 a b c d e f __m256i _val = _mm256_loadu_si256((const __m256i*)r0); __m256i _w01 = _mm256_loadu_si256((const __m256i*)k0); __m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ __m256i _val_0123 = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0)); __m256i _val_4567 = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2)); __m256i _val_89ab = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4)); __m256i _val_cdef = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6)); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val_0123); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w01, _val_89ab); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val_4567); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w23, _val_cdef); #else __m256i _val_0123_89ab = _mm256_unpacklo_epi16(_val, _val); __m256i _val_4567_cdef = _mm256_unpackhi_epi16(_val, _val); __m256i _val_0123 = _mm256_permutevar8x32_epi32(_val_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val_4567 = _mm256_permutevar8x32_epi32(_val_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val_89ab = _mm256_permutevar8x32_epi32(_val_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _val_cdef = _mm256_permutevar8x32_epi32(_val_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val_0123); __m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val_0123); __m256i _sl10_11 = _mm256_mullo_epi16(_w01, _val_89ab); __m256i _sh10_11 = _mm256_mulhi_epi16(_w01, _val_89ab); __m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val_4567); __m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val_4567); __m256i _sl12_13 = _mm256_mullo_epi16(_w23, _val_cdef); __m256i _sh12_13 = _mm256_mulhi_epi16(_w23, _val_cdef); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl12_13, _sh12_13)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl12_13, _sh12_13)); #endif #else // 0 1 2 3 4 5 6 7 __m128i _val0 = _mm_loadu_si128((const __m128i*)r0); __m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8)); __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _w1 = _mm_loadu_si128((const __m128i*)(k0 + 8)); __m128i _w2 = _mm_loadu_si128((const __m128i*)(k0 + 16)); __m128i _w3 = _mm_loadu_si128((const __m128i*)(k0 + 24)); #if __XOP__ __m128i _val0_01 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val0_23 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val0_45 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val0_67 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(3, 3, 3, 3)); __m128i _val1_01 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val1_23 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val1_45 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val1_67 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(3, 3, 3, 3)); _sum0 = _mm_maddd_epi16(_val0_01, _w0, _sum0); _sum1 = _mm_maddd_epi16(_val0_23, _w1, _sum1); _sum2 = _mm_maddd_epi16(_val1_01, _w0, _sum2); _sum3 = _mm_maddd_epi16(_val1_23, _w1, _sum3); _sum0 = _mm_maddd_epi16(_val0_45, _w2, _sum0); _sum1 = _mm_maddd_epi16(_val0_67, _w3, _sum1); _sum2 = _mm_maddd_epi16(_val1_45, _w2, _sum2); _sum3 = _mm_maddd_epi16(_val1_67, _w3, _sum3); #else // 0 0 1 1 2 2 3 3 // 4 4 5 5 6 6 7 7 __m128i _val0_0123 = _mm_unpacklo_epi16(_val0, _val0); __m128i _val0_4567 = _mm_unpackhi_epi16(_val0, _val0); __m128i _val1_0123 = _mm_unpacklo_epi16(_val1, _val1); __m128i _val1_4567 = _mm_unpackhi_epi16(_val1, _val1); __m128i _val0_01 = _mm_unpacklo_epi32(_val0_0123, _val0_0123); __m128i _val0_23 = _mm_unpackhi_epi32(_val0_0123, _val0_0123); __m128i _val0_45 = _mm_unpacklo_epi32(_val0_4567, _val0_4567); __m128i _val0_67 = _mm_unpackhi_epi32(_val0_4567, _val0_4567); __m128i _val1_01 = _mm_unpacklo_epi32(_val1_0123, _val1_0123); __m128i _val1_23 = _mm_unpackhi_epi32(_val1_0123, _val1_0123); __m128i _val1_45 = _mm_unpacklo_epi32(_val1_4567, _val1_4567); __m128i _val1_67 = _mm_unpackhi_epi32(_val1_4567, _val1_4567); __m128i _sl00 = _mm_mullo_epi16(_w0, _val0_01); __m128i _sh00 = _mm_mulhi_epi16(_w0, _val0_01); __m128i _sl10 = _mm_mullo_epi16(_w0, _val1_01); __m128i _sh10 = _mm_mulhi_epi16(_w0, _val1_01); __m128i _sl01 = _mm_mullo_epi16(_w1, _val0_23); __m128i _sh01 = _mm_mulhi_epi16(_w1, _val0_23); __m128i _sl11 = _mm_mullo_epi16(_w1, _val1_23); __m128i _sh11 = _mm_mulhi_epi16(_w1, _val1_23); __m128i _sl02 = _mm_mullo_epi16(_w2, _val0_45); __m128i _sh02 = _mm_mulhi_epi16(_w2, _val0_45); __m128i _sl12 = _mm_mullo_epi16(_w2, _val1_45); __m128i _sh12 = _mm_mulhi_epi16(_w2, _val1_45); __m128i _sl03 = _mm_mullo_epi16(_w3, _val0_67); __m128i _sh03 = _mm_mulhi_epi16(_w3, _val0_67); __m128i _sl13 = _mm_mullo_epi16(_w3, _val1_67); __m128i _sh13 = _mm_mulhi_epi16(_w3, _val1_67); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl00, _sh00)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl00, _sh00)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl10, _sh10)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl10, _sh10)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl01, _sh01)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl01, _sh01)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl11, _sh11)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl11, _sh11)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl02, _sh02)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl02, _sh02)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl12, _sh12)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl12, _sh12)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl03, _sh03)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl03, _sh03)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl13, _sh13)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl13, _sh13)); #endif #endif r0 += 16; k0 += 32; } #if __AVX2__ __m256i _sum0_2 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 2, 0, 0)); __m256i _sum1_3 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 3, 0, 1)); _sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3); _mm256_storeu_si256((__m256i*)output0_tm, _sum0_2); #else _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); _mm_storeu_si128((__m128i*)output0_tm, _sum0); _mm_storeu_si128((__m128i*)(output0_tm + 4), _sum2); #endif output0_tm += 8; } for (; i < tiles; i++) { #if __AVX2__ const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2 + i % 2); #else const short* r0 = bb2.row<const short>(i / 2 + i % 2); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 #if __AVX2__ __m256i _sum0_1 = _mm256_setzero_si256(); #else __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); #endif for (int j = 0; j < nn; j++) { // 0 1 2 3 4 5 6 7 __m128i _val = _mm_loadu_si128((const __m128i*)r0); #if __AVX2__ __m256i _w01 = _mm256_loadu_si256((const __m256i*)k0); __m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ // 0 1 0 1 x x x x // 0 1 0 1 0 1 0 1 __m128i _val_01 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val_23 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val_45 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val_67 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(3, 3, 3, 3)); __m256i _val_0123 = _mm256_inserti128_si256(_mm256_castsi128_si256(_val_01), _val_23, 1); __m256i _val_4567 = _mm256_inserti128_si256(_mm256_castsi128_si256(_val_45), _val_67, 1); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val_0123); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val_4567); #else // 0 0 1 1 2 2 3 3 // 4 4 5 5 6 6 7 7 __m256i _val_0123 = _mm256_castsi128_si256(_mm_unpacklo_epi16(_val, _val)); __m256i _val_4567 = _mm256_castsi128_si256(_mm_unpackhi_epi16(_val, _val)); _val_0123 = _mm256_permutevar8x32_epi32(_val_0123, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); _val_4567 = _mm256_permutevar8x32_epi32(_val_4567, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val_0123); __m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val_0123); __m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val_4567); __m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val_4567); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03)); #endif #else __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _w1 = _mm_loadu_si128((const __m128i*)(k0 + 8)); __m128i _w2 = _mm_loadu_si128((const __m128i*)(k0 + 16)); __m128i _w3 = _mm_loadu_si128((const __m128i*)(k0 + 24)); #if __XOP__ __m128i _val01 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val23 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val45 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val67 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(3, 3, 3, 3)); _sum0 = _mm_maddd_epi16(_val01, _w0, _sum0); _sum1 = _mm_maddd_epi16(_val23, _w1, _sum1); _sum0 = _mm_maddd_epi16(_val45, _w2, _sum0); _sum1 = _mm_maddd_epi16(_val67, _w3, _sum1); #else // 0 0 1 1 2 2 3 3 // 4 4 5 5 6 6 7 7 __m128i _val_0123 = _mm_unpacklo_epi16(_val, _val); __m128i _val_4567 = _mm_unpackhi_epi16(_val, _val); __m128i _val01 = _mm_unpacklo_epi32(_val_0123, _val_0123); __m128i _val23 = _mm_unpackhi_epi32(_val_0123, _val_0123); __m128i _val45 = _mm_unpacklo_epi32(_val_4567, _val_4567); __m128i _val67 = _mm_unpackhi_epi32(_val_4567, _val_4567); __m128i _sl0 = _mm_mullo_epi16(_w0, _val01); __m128i _sh0 = _mm_mulhi_epi16(_w0, _val01); __m128i _sl1 = _mm_mullo_epi16(_w1, _val23); __m128i _sh1 = _mm_mulhi_epi16(_w1, _val23); __m128i _sl2 = _mm_mullo_epi16(_w2, _val45); __m128i _sh2 = _mm_mulhi_epi16(_w2, _val45); __m128i _sl3 = _mm_mullo_epi16(_w3, _val67); __m128i _sh3 = _mm_mulhi_epi16(_w3, _val67); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl1, _sh1)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl2, _sh2)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl2, _sh2)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl3, _sh3)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl3, _sh3)); #endif #endif r0 += 8; k0 += 32; } #if __AVX2__ __m128i _sum0 = _mm256_extracti128_si256(_sum0_1, 0); __m128i _sum1 = _mm256_extracti128_si256(_sum0_1, 1); #endif _sum0 = _mm_add_epi32(_sum0, _sum1); _mm_storeu_si128((__m128i*)output0_tm, _sum0); output0_tm += 4; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u * 4, 4, opt.workspace_allocator); } { // const float otm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + (r01 + r02) + (r03 + r04) // 1 = (r01 - r02) + (r03 - r04) * 2 // 2 = (r01 + r02) + (r03 + r04) * 4 // 3 = r05 + (r01 - r02) + (r03 - r04) * 8 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); int tmp[4][6][4]; // tile for (int i = 0; i < outh / 4; i++) { for (int j = 0; j < outw / 4; j++) { // top_blob_tm.create(tiles, 36, outch, elemsize, elempack); const int* output0_tm_0 = (const int*)out0_tm + (i * w_tm / 6 + j) * 4; const int* output0_tm_1 = output0_tm_0 + tiles * 4; const int* output0_tm_2 = output0_tm_0 + tiles * 8; const int* output0_tm_3 = output0_tm_0 + tiles * 12; const int* output0_tm_4 = output0_tm_0 + tiles * 16; const int* output0_tm_5 = output0_tm_0 + tiles * 20; int* output0 = out0.row<int>(i * 4) + (j * 4) * 4; // TODO sse optimize for (int m = 0; m < 5; m++) { __m128i _out0tm0 = _mm_loadu_si128((const __m128i*)output0_tm_0); __m128i _out0tm1 = _mm_loadu_si128((const __m128i*)output0_tm_1); __m128i _out0tm2 = _mm_loadu_si128((const __m128i*)output0_tm_2); __m128i _out0tm3 = _mm_loadu_si128((const __m128i*)output0_tm_3); __m128i _out0tm4 = _mm_loadu_si128((const __m128i*)output0_tm_4); __m128i _out0tm5 = _mm_loadu_si128((const __m128i*)output0_tm_5); __m128i _tmp02a = _mm_add_epi32(_out0tm1, _out0tm2); __m128i _tmp13a = _mm_sub_epi32(_out0tm1, _out0tm2); __m128i _tmp02b = _mm_add_epi32(_out0tm3, _out0tm4); __m128i _tmp13b = _mm_sub_epi32(_out0tm3, _out0tm4); __m128i _tmp0m = _mm_add_epi32(_mm_add_epi32(_out0tm0, _tmp02a), _tmp02b); __m128i _tmp1m = _mm_add_epi32(_tmp13a, _mm_slli_epi32(_tmp13b, 1)); __m128i _tmp2m = _mm_add_epi32(_tmp02a, _mm_slli_epi32(_tmp02b, 2)); __m128i _tmp3m = _mm_add_epi32(_mm_add_epi32(_tmp13a, _mm_slli_epi32(_out0tm5, 2)), _mm_slli_epi32(_tmp13b, 3)); _mm_storeu_si128((__m128i*)tmp[0][m], _tmp0m); _mm_storeu_si128((__m128i*)tmp[1][m], _tmp1m); _mm_storeu_si128((__m128i*)tmp[2][m], _tmp2m); _mm_storeu_si128((__m128i*)tmp[3][m], _tmp3m); output0_tm_0 += tiles * 24; output0_tm_1 += tiles * 24; output0_tm_2 += tiles * 24; output0_tm_3 += tiles * 24; output0_tm_4 += tiles * 24; output0_tm_5 += tiles * 24; } for (int m = 5; m < 6; m++) { __m128i _out0tm0 = _mm_loadu_si128((const __m128i*)output0_tm_0); __m128i _out0tm1 = _mm_loadu_si128((const __m128i*)output0_tm_1); __m128i _out0tm2 = _mm_loadu_si128((const __m128i*)output0_tm_2); __m128i _out0tm3 = _mm_loadu_si128((const __m128i*)output0_tm_3); __m128i _out0tm4 = _mm_loadu_si128((const __m128i*)output0_tm_4); __m128i _out0tm5 = _mm_loadu_si128((const __m128i*)output0_tm_5); __m128i _tmp02a = _mm_add_epi32(_out0tm1, _out0tm2); __m128i _tmp13a = _mm_sub_epi32(_out0tm1, _out0tm2); __m128i _tmp02b = _mm_add_epi32(_out0tm3, _out0tm4); __m128i _tmp13b = _mm_sub_epi32(_out0tm3, _out0tm4); __m128i _tmp0m = _mm_add_epi32(_mm_add_epi32(_out0tm0, _tmp02a), _tmp02b); __m128i _tmp1m = _mm_add_epi32(_tmp13a, _mm_slli_epi32(_tmp13b, 1)); __m128i _tmp2m = _mm_add_epi32(_tmp02a, _mm_slli_epi32(_tmp02b, 2)); __m128i _tmp3m = _mm_add_epi32(_mm_add_epi32(_tmp13a, _mm_slli_epi32(_out0tm5, 2)), _mm_slli_epi32(_tmp13b, 3)); _tmp0m = _mm_slli_epi32(_tmp0m, 2); _tmp1m = _mm_slli_epi32(_tmp1m, 2); _tmp2m = _mm_slli_epi32(_tmp2m, 2); _tmp3m = _mm_slli_epi32(_tmp3m, 2); _mm_storeu_si128((__m128i*)tmp[0][m], _tmp0m); _mm_storeu_si128((__m128i*)tmp[1][m], _tmp1m); _mm_storeu_si128((__m128i*)tmp[2][m], _tmp2m); _mm_storeu_si128((__m128i*)tmp[3][m], _tmp3m); output0_tm_0 += tiles * 24; output0_tm_1 += tiles * 24; output0_tm_2 += tiles * 24; output0_tm_3 += tiles * 24; output0_tm_4 += tiles * 24; output0_tm_5 += tiles * 24; } for (int m = 0; m < 4; m++) { __m128i _tmp00 = _mm_loadu_si128((const __m128i*)tmp[m][0]); __m128i _tmp01 = _mm_loadu_si128((const __m128i*)tmp[m][1]); __m128i _tmp02 = _mm_loadu_si128((const __m128i*)tmp[m][2]); __m128i _tmp03 = _mm_loadu_si128((const __m128i*)tmp[m][3]); __m128i _tmp04 = _mm_loadu_si128((const __m128i*)tmp[m][4]); __m128i _tmp05 = _mm_loadu_si128((const __m128i*)tmp[m][5]); __m128i _tmp02a = _mm_add_epi32(_tmp01, _tmp02); __m128i _tmp13a = _mm_sub_epi32(_tmp01, _tmp02); __m128i _tmp02b = _mm_add_epi32(_tmp03, _tmp04); __m128i _tmp13b = _mm_sub_epi32(_tmp03, _tmp04); __m128i _out00 = _mm_add_epi32(_mm_add_epi32(_tmp00, _tmp02a), _tmp02b); __m128i _out01 = _mm_add_epi32(_tmp13a, _mm_slli_epi32(_tmp13b, 1)); __m128i _out02 = _mm_add_epi32(_tmp02a, _mm_slli_epi32(_tmp02b, 2)); __m128i _out03 = _mm_add_epi32(_mm_add_epi32(_tmp05, _tmp13a), _mm_slli_epi32(_tmp13b, 3)); // TODO use integer trick for division by 576 __m128 _v576 = _mm_set1_ps(1.0 / 576); _out00 = _mm_cvttps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(_out00), _v576)); _out01 = _mm_cvttps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(_out01), _v576)); _out02 = _mm_cvttps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(_out02), _v576)); _out03 = _mm_cvttps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(_out03), _v576)); _mm_storeu_si128((__m128i*)output0, _out00); _mm_storeu_si128((__m128i*)(output0 + 4), _out01); _mm_storeu_si128((__m128i*)(output0 + 8), _out02); _mm_storeu_si128((__m128i*)(output0 + 12), _out03); output0 += outw * 4; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
copyprivate-clauseModificado.c
#include <stdio.h> #include <omp.h> int main(){ int n= 9, i, b[n]; for(i=0;i<n;i++) b[i]=-1; #pragma omp parallel { int a; #pragma omp single { printf("\nIntroduce valor de inicialización de a:"); scanf("%d",&a); printf("\nSingle ejectuada por el thread %d\n",omp_get_thread_num()); } #pragma omp for for(i=0; i<n; i++) b[i] = a; } printf("Después de la región parallel:\n"); for(i=0;i<n;i++) printf("b[%d] = %d\n",i,b[i]); printf("\n"); }
target-data-6c.c
// ---------------------------------------------------------------------------------------- // Implementation of Example target.3c (Section 52.3, page 196) from Openmp // 4.0.2 Examples // on the document http://openmp.org/mp-documents/openmp-examples-4.0.2.pdf // // // // // ---------------------------------------------------------------------------------------- #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #ifdef _OPENMP #include <omp.h> #endif #include "BenchmarksUtil.h" // define the error threshold for the results "not matching" #define ERROR_THRESHOLD 0.05 /* Problem size */ #define N 8192 #define THRESHOLD 4096 /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void init(DATA_TYPE *A, DATA_TYPE *B) { int i; for (i = 0; i < N; i++) { A[i] = i / 2.0; B[i] = ((N - 1) - i) / 3.0; } return; } void init_again(DATA_TYPE *A, DATA_TYPE *B) { int i; for (i = 0; i < N; i++) { A[i] = i; B[i] = ((N - 1) - i); } return; } void vec_mult(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C) { int i; for (i = 0; i < N; i++) C[i] = A[i] * B[i]; init_again(A, B); for (i = 0; i < N; i++) C[i] += A[i] * B[i]; } void vec_mult_OMP(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C) { int i; #pragma omp target data if (N > THRESHOLD) map(from : C[ : N]) { #pragma omp target if (N > THRESHOLD) map(to : A[ : N], B[ : N]) #pragma omp parallel for for (i = 0; i < N; i++) C[i] = A[i] * B[i]; init_again(A, B); #pragma omp target if (N > THRESHOLD) map(to : A[ : N], B[ : N]) #pragma omp parallel for for (i = 0; i < N; i++) C[i] += A[i] * B[i]; } } int compareResults(DATA_TYPE *B, DATA_TYPE *B_GPU) { int i, fail; fail = 0; // Compare B and B_GPU for (i = 0; i < N; i++) { if (B[i] != B_GPU[i]) printf("DIFF @ %d![%f, %f]\n", i, B[i], B_GPU[i]); if (percentDiff(B[i], B_GPU[i]) > ERROR_THRESHOLD) { fail++; } } // Print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f " "Percent: %d\n", ERROR_THRESHOLD, fail); return fail; } int main(int argc, char *argv[]) { double t_start, t_end, t_start_OMP, t_end_OMP; int fail = 0; DATA_TYPE *A; DATA_TYPE *B; DATA_TYPE *C; DATA_TYPE *C_OMP; A = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE)); B = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE)); C = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE)); C_OMP = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE)); fprintf(stdout, ">> Two vector multiplication <<\n"); // initialize the arrays init(A, B); t_start_OMP = rtclock(); vec_mult_OMP(A, B, C_OMP); t_end_OMP = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end_OMP - t_start_OMP); //); #ifdef RUN_TEST // initialize the arrays init(A, B); t_start = rtclock(); vec_mult(A, B, C); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); //); fail = compareResults(C, C_OMP); #endif free(A); free(B); free(C); free(C_OMP); return fail; }
seq_multivector.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "seq_multivector.h" #include "_hypre_utilities.h" #include <stdlib.h> #include <string.h> #include <assert.h> /*-------------------------------------------------------------------------- * hypre_SeqMultivectorCreate *--------------------------------------------------------------------------*/ hypre_Multivector * hypre_SeqMultivectorCreate( HYPRE_Int size, HYPRE_Int num_vectors ) { hypre_Multivector *mvector; mvector = (hypre_Multivector *) hypre_MAlloc(sizeof(hypre_Multivector)); hypre_MultivectorNumVectors(mvector) = num_vectors; hypre_MultivectorSize(mvector) = size; hypre_MultivectorOwnsData(mvector) = 1; hypre_MultivectorData(mvector) = NULL; mvector->num_active_vectors=0; mvector->active_indices=NULL; return mvector; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInitialize( hypre_Multivector *mvector ) { HYPRE_Int ierr = 0, i, size, num_vectors; size = hypre_MultivectorSize(mvector); num_vectors = hypre_MultivectorNumVectors(mvector); if (NULL==hypre_MultivectorData(mvector)) hypre_MultivectorData(mvector) = (HYPRE_Complex *) hypre_MAlloc(sizeof(HYPRE_Complex)*size*num_vectors); /* now we create a "mask" of "active" vectors; initially all active */ if (NULL==mvector->active_indices) { mvector->active_indices=hypre_CTAlloc(HYPRE_Int, num_vectors); for (i=0; i<num_vectors; i++) mvector->active_indices[i] = i; mvector->num_active_vectors=num_vectors; } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetDataOwner(hypre_Multivector *mvector, HYPRE_Int owns_data) { HYPRE_Int ierr=0; hypre_MultivectorOwnsData(mvector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorDestroy(hypre_Multivector *mvector) { HYPRE_Int ierr=0; if (NULL!=mvector) { if (hypre_MultivectorOwnsData(mvector) && NULL!=hypre_MultivectorData(mvector)) hypre_TFree( hypre_MultivectorData(mvector) ); if (NULL!=mvector->active_indices) hypre_TFree(mvector->active_indices); hypre_TFree(mvector); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetMask * (this routine accepts mask in "zeros and ones format, and converts it to the one used in the structure "hypre_Multivector") *-------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetMask(hypre_Multivector *mvector, HYPRE_Int * mask) { HYPRE_Int i, num_vectors = mvector->num_vectors; if (mvector->active_indices != NULL) hypre_TFree(mvector->active_indices); mvector->active_indices=hypre_CTAlloc(HYPRE_Int, num_vectors); mvector->num_active_vectors=0; if (mask!=NULL) for (i=0; i<num_vectors; i++) { if ( mask[i] ) mvector->active_indices[mvector->num_active_vectors++]=i; } else for (i=0; i<num_vectors; i++) mvector->active_indices[mvector->num_active_vectors++]=i; return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetConstantValues(hypre_Multivector *v, HYPRE_Complex value) { HYPRE_Int i, j, start_offset, end_offset; HYPRE_Int size = hypre_MultivectorSize(v); HYPRE_Complex *vector_data = hypre_MultivectorData(v); if (v->num_active_vectors == v->num_vectors) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < v->num_vectors*size; j++) vector_data[j] = value; } else { for (i = 0; i < v->num_active_vectors; i++) { start_offset = v->active_indices[i]*size; end_offset = start_offset+size; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = start_offset; j < end_offset; j++) vector_data[j]= value; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetRandomValues * * returns vector of values randomly distributed between -1.0 and +1.0 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetRandomValues(hypre_Multivector *v, HYPRE_Int seed) { HYPRE_Int i, j, start_offset, end_offset; HYPRE_Int size = hypre_MultivectorSize(v); HYPRE_Complex *vector_data = hypre_MultivectorData(v); hypre_SeedRand(seed); /* comment from vector.c: RDF: threading this loop may cause problems because of hypre_Rand() */ if (v->num_active_vectors == v->num_vectors) { for (j = 0; j < v->num_vectors*size; j++) vector_data[j] = 2.0 * hypre_Rand() - 1.0; } else { for (i = 0; i < v->num_active_vectors; i++) { start_offset = v->active_indices[i]*size; end_offset = start_offset+size; for (j = start_offset; j < end_offset; j++) vector_data[j]= 2.0 * hypre_Rand() - 1.0; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorCopy * copies data from x to y * y should have already been initialized at the same size as x *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorCopy(hypre_Multivector *x, hypre_Multivector *y) { HYPRE_Int i, size, num_bytes, num_active_vectors, *x_active_ind, * y_active_ind; HYPRE_Complex *x_data, *y_data, *dest, * src; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); num_active_vectors = x->num_active_vectors; size = x->size; x_data = x->data; y_data = y->data; x_active_ind=x->active_indices; y_active_ind=y->active_indices; if (x->num_active_vectors == x->num_vectors && y->num_active_vectors == y->num_vectors) { num_bytes = x->num_vectors * size * sizeof(HYPRE_Complex); memcpy(y_data, x_data, num_bytes); } else { num_bytes = size*sizeof(HYPRE_Complex); for (i=0; i < num_active_vectors; i++) { src=x_data + size * x_active_ind[i]; dest = y_data + size * y_active_ind[i]; memcpy(dest,src,num_bytes); } } return 0; } HYPRE_Int hypre_SeqMultivectorCopyWithoutMask(hypre_Multivector *x , hypre_Multivector *y) { HYPRE_Int byte_count; hypre_assert (x->size == y->size && x->num_vectors == y->num_vectors); byte_count = sizeof(HYPRE_Complex) * x->size * x->num_vectors; memcpy(y->data,x->data,byte_count); return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorAxpy(HYPRE_Complex alpha, hypre_Multivector *x, hypre_Multivector *y) { HYPRE_Int i, j, size, num_active_vectors, *x_active_ind, *y_active_ind; HYPRE_Complex *x_data, *y_data, *src, *dest; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; if (x->num_active_vectors == x->num_vectors && y->num_active_vectors == y->num_vectors) { for(i = 0; i < x->num_vectors*size; i++) dest[i] += alpha * src[i]; } else { for(i = 0; i < num_active_vectors; i++) { src = x_data + x_active_ind[i]*size; dest = y_data + y_active_ind[i]*size; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < size; j++) dest[j] += alpha * src[j]; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorByDiag: " y(<y_mask>) = alpha(<mask>) .* x(<x_mask>) " *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorByDiag(hypre_Multivector *x, HYPRE_Int *mask, HYPRE_Int n, HYPRE_Complex *alpha, hypre_Multivector *y) { HYPRE_Int i, j, size, num_active_vectors, *x_active_ind, *y_active_ind; HYPRE_Int *al_active_ind, num_active_als; HYPRE_Complex *x_data, *y_data, *dest, *src, current_alpha; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); /* build list of active indices in alpha */ al_active_ind = hypre_TAlloc(HYPRE_Int,n); num_active_als = 0; if (mask!=NULL) for (i=0; i<n; i++) { if (mask[i]) al_active_ind[num_active_als++]=i; } else for (i=0; i<n; i++) al_active_ind[num_active_als++]=i; hypre_assert (num_active_als==x->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; for(i = 0; i < num_active_vectors; i++) { src = x_data + x_active_ind[i]*size; dest = y_data + y_active_ind[i]*size; current_alpha=alpha[ al_active_ind[i] ]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < size; j++) dest[j] = current_alpha*src[j]; } hypre_TFree(al_active_ind); return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInnerProd(hypre_Multivector *x, hypre_Multivector *y, HYPRE_Real *results ) { HYPRE_Int i, j, k, size, *x_active_ind, *y_active_ind; HYPRE_Int x_num_active_vectors, y_num_active_vectors; HYPRE_Complex *x_data, *y_data, *y_ptr, *x_ptr; HYPRE_Real current_product; hypre_assert (x->size==y->size); x_data = x->data; y_data = y->data; size = x->size; x_num_active_vectors = x->num_active_vectors; y_num_active_vectors = y->num_active_vectors; /* we assume that "results" points to contiguous array of (x_num_active_vectors X y_num_active_vectors) doubles */ x_active_ind = x->active_indices; y_active_ind = y->active_indices; for(j = 0; j < y_num_active_vectors; j++) { y_ptr = y_data + y_active_ind[j]*size; for (i = 0; i < x_num_active_vectors; i++) { x_ptr = x_data + x_active_ind[i]*size; current_product = 0.0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) reduction(+:current_product) HYPRE_SMP_SCHEDULE #endif for(k = 0; k < size; k++) current_product += x_ptr[k] * hypre_conj(y_ptr[k]); /* column-wise storage for results */ *results++ = current_product; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInnerProdDiag *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInnerProdDiag(hypre_Multivector *x, hypre_Multivector *y, HYPRE_Real *diagResults) { HYPRE_Complex *x_data, *y_data, *y_ptr, *x_ptr; HYPRE_Real current_product; HYPRE_Int i, k, size, num_active_vectors, *x_active_ind, *y_active_ind; hypre_assert(x->size==y->size && x->num_active_vectors == y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; for (i=0; i<num_active_vectors; i++) { x_ptr = x_data + x_active_ind[i]*size; y_ptr = y_data + y_active_ind[i]*size; current_product = 0.0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) reduction(+:current_product) HYPRE_SMP_SCHEDULE #endif for(k=0; k<size; k++) current_product += x_ptr[k] * hypre_conj(y_ptr[k]); *diagResults++ = current_product; } return 0; } HYPRE_Int hypre_SeqMultivectorByMatrix(hypre_Multivector *x, HYPRE_Int rGHeight, HYPRE_Int rHeight, HYPRE_Int rWidth, HYPRE_Complex* rVal, hypre_Multivector *y) { HYPRE_Int i, j, k, size, gap, *x_active_ind, *y_active_ind; HYPRE_Complex *x_data, *y_data, *x_ptr, *y_ptr, current_coef; hypre_assert(rHeight>0); hypre_assert (rHeight==x->num_active_vectors && rWidth==y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; x_active_ind = x->active_indices; y_active_ind = y->active_indices; gap = rGHeight - rHeight; for (j=0; j<rWidth; j++) { y_ptr = y_data + y_active_ind[j]*size; /* ------ set current "y" to first member in a sum ------ */ x_ptr = x_data + x_active_ind[0]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] = current_coef * x_ptr[k]; /* ------ now add all other members of a sum to "y" ----- */ for (i=1; i<rHeight; i++) { x_ptr = x_data + x_active_ind[i]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] += current_coef * x_ptr[k]; } rVal += gap; } return 0; } HYPRE_Int hypre_SeqMultivectorXapy (hypre_Multivector *x, HYPRE_Int rGHeight, HYPRE_Int rHeight, HYPRE_Int rWidth, HYPRE_Complex* rVal, hypre_Multivector *y) { HYPRE_Complex *x_data, *y_data, *x_ptr, *y_ptr, current_coef; HYPRE_Int i, j, k, size, gap, *x_active_ind, *y_active_ind; hypre_assert (rHeight==x->num_active_vectors && rWidth==y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; x_active_ind = x->active_indices; y_active_ind = y->active_indices; gap = rGHeight - rHeight; for (j=0; j<rWidth; j++) { y_ptr = y_data + y_active_ind[j]*size; for (i=0; i<rHeight; i++) { x_ptr = x_data + x_active_ind[i]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] += current_coef * x_ptr[k]; } rVal += gap; } return 0; }
vect-outer-simd-3.c
/* { dg-require-effective-target vect_simd_clones } */ /* { dg-additional-options "-O3 -fopenmp-simd -ffast-math" } */ #include <stdlib.h> #include "tree-vect.h" #define N 64 float *px, *py; float *tx, *ty; float *x1, *z1, *t1, *t2; int bound[N]; static void inline bar(const float cx, float cy, float *vx, float *vy, int n) { int j; for (j = 0; j < n; ++j) { const float dx = cx - px[j]; const float dy = cy - py[j]; *vx -= dx * tx[j]; *vy -= dy * ty[j]; } } __attribute__((noinline, noclone)) void foo1 () { int i; int n = bound[63]; #pragma omp simd for (i=0; i<N; i++) bar(px[i], py[i], x1+i, z1+i, n); } __attribute__((noinline, noclone)) void foo2 () { volatile int i; int n = bound[63]; for (i=0; i<N; i++) bar(px[i], py[i], x1+i, z1+i, n); } int main() { float *X = (float*)malloc(N * 8 * sizeof (float)); int i; /* check_vect (); */ px = &X[0]; py = &X[N * 1]; tx = &X[N * 2]; ty = &X[N * 3]; x1 = &X[N * 4]; z1 = &X[N * 5]; t1 = &X[N * 6]; t2 = &X[N * 7]; for (i=0; i<N; i++) { px[i] = (float) (i+2); tx[i] = (float) (i+1); py[i] = (float) (i+4); ty[i] = (float) (i+3); x1[i] = z1[i] = 1.0f; bound[i] = i + 1; } foo1 (); /* vector variant. */ for (i=0; i<N;i++) { t1[i] = x1[i]; x1[i] = 1.0f; t2[i] = z1[i]; z1[i] = 1.0f; } foo2 (); /* scalar variant. */ for (i=0; i<N; i++) if (x1[i] != t1[i] || z1[i] != t2[i]) abort (); return 0; } /* { dg-final { scan-tree-dump "OUTER LOOP VECTORIZED" "vect" } } */
transpose.h
// Copyright 2018 Xiaomi, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACE_KERNELS_TRANSPOSE_H_ #define MACE_KERNELS_TRANSPOSE_H_ #if defined(MACE_ENABLE_NEON) #include <arm_neon.h> #endif #include <vector> #include "mace/core/future.h" #include "mace/core/tensor.h" #include "mace/public/mace.h" #include "mace/utils/utils.h" namespace mace { namespace kernels { static void TransposeNHWCToNCHWC3(const float *input, float *output, const index_t height, const index_t width) { index_t image_size = height * width; #pragma omp parallel for for (index_t h = 0; h < height; ++h) { index_t in_offset = h * width * 3; index_t out_offset = h * width; #if defined(MACE_ENABLE_NEON) index_t w; for (w = 0; w + 3 < width; w += 4) { float32x4x3_t vi = vld3q_f32(input + in_offset); vst1q_f32(output + out_offset, vi.val[0]); vst1q_f32(output + out_offset + image_size, vi.val[1]); vst1q_f32(output + out_offset + image_size * 2, vi.val[2]); in_offset += 12; out_offset += 4; } for (; w < width; ++w) { for (index_t c = 0; c < 3; ++c) { output[h * width + image_size * c + w] = input[h * width * 3 + w * 3 + c]; } } #else for (index_t w = 0; w < width; ++w) { for (index_t c = 0; c < 3; ++c) { output[out_offset + c * image_size + w] = input[in_offset + w * 3 + c]; } } #endif } } static void TransposeNCHWToNHWCC2(const float *input, float *output, const index_t height, const index_t width) { index_t image_size = height * width; #pragma omp parallel for for (index_t h = 0; h < height; ++h) { index_t in_offset = h * width; index_t out_offset = h * width * 2; #if defined(MACE_ENABLE_NEON) index_t w; for (w = 0; w + 3 < width; w += 4) { float32x4_t vi0 = vld1q_f32(input + in_offset); float32x4_t vi1 = vld1q_f32(input + in_offset + image_size); float32x4x2_t vi = {vi0, vi1}; vst2q_f32(output + out_offset, vi); in_offset += 4; out_offset += 8; } for (; w < width; ++w) { for (index_t c = 0; c < 2; ++c) { output[h * width * 2 + w * 2 + c] = input[h * width + image_size * c + w]; } } #else for (index_t w = 0; w < width; ++w) { for (index_t c = 0; c < 2; ++c) { output[out_offset + w * 2 + c] = input[in_offset + c * image_size + w]; } } #endif } } template<DeviceType D, typename T> struct TransposeFunctor { explicit TransposeFunctor(const std::vector<int> &dims) : dims_(dims) {} MaceStatus operator()(const Tensor *input, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); Tensor::MappingGuard input_guard(input); Tensor::MappingGuard output_guard(output); const std::vector<index_t> &input_shape = input->shape(); const std::vector<index_t> &output_shape = output->shape(); const T *input_data = input->data<T>(); T *output_data = output->mutable_data<T>(); if (input->dim_size() == 2) { MACE_CHECK(dims_[0] == 1 && dims_[1] == 0, "no need transform"); index_t stride_i = input_shape[0]; index_t stride_j = input_shape[1]; for (int i = 0; i < input_shape[0]; ++i) { for (int j = 0; j < input_shape[1]; ++j) { output_data[j * stride_i + i] = input_data[i * stride_j + j]; } } } else if (input->dim_size() == 4) { std::vector<int> transpose_order_from_NHWC_to_NCHW{0, 3, 1, 2}; std::vector<int> transpose_order_from_NCHW_to_NHWC{0, 2, 3, 1}; index_t batch_size = input->dim(1) * input->dim(2) * input->dim(3); if (dims_ == transpose_order_from_NHWC_to_NCHW && input->dim(3) == 3) { for (index_t b = 0; b < input->dim(0); ++b) { TransposeNHWCToNCHWC3(input_data + b * batch_size, output_data + b * batch_size, input->dim(1), input->dim(2)); } } else if (dims_ == transpose_order_from_NCHW_to_NHWC && input->dim(1) == 2) { for (index_t b = 0; b < input->dim(0); ++b) { TransposeNCHWToNHWCC2(input_data + b * batch_size, output_data + b * batch_size, input->dim(2), input->dim(3)); } } else { std::vector<index_t> in_stride{input_shape[1] * input_shape[2] * input_shape[3], input_shape[2] * input_shape[3], input_shape[3], 1}; std::vector<index_t> out_stride{output_shape[1] * output_shape[2] * output_shape[3], output_shape[2] * output_shape[3], output_shape[3], 1}; std::vector<index_t> idim(4, 0); std::vector<index_t> odim(4, 0); for (odim[0] = 0; odim[0] < output_shape[0]; ++odim[0]) { for (odim[1] = 0; odim[1] < output_shape[1]; ++odim[1]) { for (odim[2] = 0; odim[2] < output_shape[2]; ++odim[2]) { for (odim[3] = 0; odim[3] < output_shape[3]; ++odim[3]) { idim[dims_[0]] = odim[0]; idim[dims_[1]] = odim[1]; idim[dims_[2]] = odim[2]; idim[dims_[3]] = odim[3]; output_data[odim[0] * out_stride[0] + odim[1] * out_stride[1] + odim[2] * out_stride[2] + odim[3]] = input_data[idim[0] * in_stride[0] + idim[1] * in_stride[1] + idim[2] * in_stride[2] + idim[3]]; } } } } } } else { MACE_NOT_IMPLEMENTED; } return MACE_SUCCESS; } std::vector<int> dims_; }; } // namespace kernels } // namespace mace #endif // MACE_KERNELS_TRANSPOSE_H_
genScalData.c
#include "defs.h" /* Set this variable to zero to run the data generator on one thread (for debugging purposes) */ #define PARALLEL_SDG 0 double genScalData(graphSDG* SDGdata) { VERT_T *src, *dest; WEIGHT_T *wt; LONG_T n, m; VERT_T *permV; #ifdef _OPENMP omp_lock_t* vLock; #endif double elapsed_time; int seed; n = N; m = M; /* allocate memory for edge tuples */ src = (VERT_T *) malloc(M*sizeof(VERT_T)); dest = (VERT_T *) malloc(M*sizeof(VERT_T)); assert(src != NULL); assert(dest != NULL); /* sprng seed */ seed = 2387; elapsed_time = get_seconds(); #ifdef _OPENMP #if PARALLEL_SDG omp_set_num_threads(omp_get_max_threads()); // omp_set_num_threads(16); #else omp_set_num_threads(1); #endif #endif #ifdef _OPENMP #pragma omp parallel { #endif int tid, nthreads; #ifdef DIAGNOSTIC double elapsed_time_part; #endif int *stream; LONG_T i, j, u, v, step; DOUBLE_T av, bv, cv, dv, p, S, var; LONG_T tmpVal; #ifdef _OPENMP nthreads = omp_get_num_threads(); tid = omp_get_thread_num(); #else nthreads = 1; tid = 0; #endif /* Initialize RNG stream */ stream = init_sprng(0, tid, nthreads, seed, SPRNG_DEFAULT); #ifdef DIAGNOSTIC if (tid == 0) elapsed_time_part = get_seconds(); #endif /* Start adding edges */ #ifdef _OPENMP #pragma omp for #endif for (i=0; i<m; i++) { u = 1; v = 1; step = n/2; av = A; bv = B; cv = C; dv = D; p = sprng(stream); if (p < av) { /* Do nothing */ } else if ((p >= av) && (p < av+bv)) { v += step; } else if ((p >= av+bv) && (p < av+bv+cv)) { u += step; } else { u += step; v += step; } for (j=1; j<SCALE; j++) { step = step/2; /* Vary a,b,c,d by up to 10% */ var = 0.1; av *= 0.95 + var * sprng(stream); bv *= 0.95 + var * sprng(stream); cv *= 0.95 + var * sprng(stream); dv *= 0.95 + var * sprng(stream); S = av + bv + cv + dv; av = av/S; bv = bv/S; cv = cv/S; dv = dv/S; /* Choose partition */ p = sprng(stream); if (p < av) { /* Do nothing */ } else if ((p >= av) && (p < av+bv)) { v += step; } else if ((p >= av+bv) && (p < av+bv+cv)) { u += step; } else { u += step; v += step; } } src[i] = u-1; dest[i] = v-1; } #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() -elapsed_time_part; fprintf(stderr, "Tuple generation time: %lf seconds\n", elapsed_time_part); elapsed_time_part = get_seconds(); } #endif /* Generate vertex ID permutations */ if (tid == 0) { permV = (VERT_T *) malloc(N*sizeof(VERT_T)); assert(permV != NULL); } #ifdef _OPENMP #pragma omp barrier #pragma omp for #endif for (i=0; i<n; i++) { permV[i] = i; } #ifdef _OPENMP if (tid == 0) { vLock = (omp_lock_t *) malloc(n*sizeof(omp_lock_t)); assert(vLock != NULL); } #pragma omp barrier #pragma omp for for (i=0; i<n; i++) { omp_init_lock(&vLock[i]); } #endif #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) { j = n*sprng(stream); if (i != j) { #ifdef _OPENMP int l1 = omp_test_lock(&vLock[i]); if (l1) { int l2 = omp_test_lock(&vLock[j]); if (l2) { #endif tmpVal = permV[i]; permV[i] = permV[j]; permV[j] = tmpVal; #ifdef _OPENMP omp_unset_lock(&vLock[j]); } omp_unset_lock(&vLock[i]); } #endif } } #ifdef _OPENMP #pragma omp for for (i=0; i<n; i++) { omp_destroy_lock(&vLock[i]); } #pragma omp barrier if (tid == 0) { free(vLock); } #endif #ifdef _OPENMP #pragma omp for #endif for (i=0; i<m; i++) { src[i] = permV[src[i]]; dest[i] = permV[dest[i]]; } #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() - elapsed_time_part; fprintf(stderr, "Permuting vertex IDs: %lf seconds\n", elapsed_time_part); elapsed_time_part = get_seconds(); } #endif if (tid == 0) { free(permV); } /* Generate edge weights */ if (tid == 0) { wt = (WEIGHT_T *) malloc(M*sizeof(WEIGHT_T)); assert(wt != NULL); } #ifdef _OPENMP #pragma omp barrier #pragma omp for #endif for (i=0; i<m; i++) { wt[i] = 1 + MaxIntWeight * sprng(stream); } #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() - elapsed_time_part; fprintf(stderr, "Generating edge weights: %lf seconds\n", elapsed_time_part); elapsed_time_part = get_seconds(); } #endif SDGdata->n = n; SDGdata->m = m; SDGdata->startVertex = src; SDGdata->endVertex = dest; SDGdata->weight = wt; free_sprng(stream); #ifdef _OPENMP } #endif elapsed_time = get_seconds() - elapsed_time; return elapsed_time; }
mandelbrot-7.c
/* The Computer Language Benchmarks Game http://benchmarksgame.alioth.debian.org/ contributed by Paolo Bonzini further optimized by Jason Garrett-Glaser OpenMP by The Anh Tran 10-11-2010, modified by The Anh Tran: _ copy bit shift idea from C entry C version by Des Nerger */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <sched.h> #include <memory.h> #include <omp.h> #include <sys/types.h> #define L2_CACHE_LINE 64 #define ALIGN __attribute__ ((aligned(L2_CACHE_LINE))) typedef unsigned char byte; typedef double v2d __attribute__ ((vector_size(16))); typedef int32_t v4i __attribute__ ((vector_size(16))); const v2d v10 = { 1.0, 1.0 }; const v2d v15 = { 1.5, 1.5 }; const v2d v40 = { 4.0, 4.0 }; v2d inv_2n; // {2.0/N, 2.0/N} int GetThreadCount() { cpu_set_t cs; CPU_ZERO(&cs); sched_getaffinity(0, sizeof(cs), &cs); int count = 0; for (int i = 0; i < CPU_SETSIZE; ++i) count += CPU_ISSET(i, &cs); return count; } void mandelbrot(int N, byte* data) { ALIGN int row_processed = 0; #pragma omp parallel default(shared) num_threads(GetThreadCount()) { int y = 0; while ((y = __sync_fetch_and_add(&row_processed, 1)) < N) { byte* row_output = data + y * (N >> 3); v2d Civ = {y, y}; Civ = Civ * inv_2n - v10; for (int x = 0; x < N; x += 2) { v2d Crv = {x+1, x}; Crv = Crv * inv_2n - v15; v2d Zrv = Crv; v2d Ziv = Civ; v2d Trv = Crv * Crv; v2d Tiv = Civ * Civ; int result = 3; // assume that 2 elements belong to MB set int i = 1; while ( result && (i++ < 50) ) { v2d ZZ = Zrv * Ziv; Zrv = Trv - Tiv + Crv; Ziv = ZZ + ZZ + Civ; Trv = Zrv * Zrv; Tiv = Ziv * Ziv; // trv + tiv <= 4.0 v2d delta = (v2d)__builtin_ia32_cmplepd( (Trv + Tiv), v40 ); result = __builtin_ia32_movmskpd(delta); } { int bit_shift = 6 - (x & 7); row_output[x >> 3] |= (byte)(result << bit_shift); } } } } } int main (int argc, char **argv) { const int N = (argc == 2) ? (int)strtol(argv[1], NULL, 10) : 200; assert((N % 8) == 0); printf("P4\n%d %d\n", N, N); { double* p_iv = (double*)(&inv_2n); p_iv[0] = p_iv[1] = 2.0 / N; } const int bytes_count = (N >> 3) * N; byte* data = 0; assert( posix_memalign((void**)(&data), L2_CACHE_LINE, bytes_count) == 0); memset(data, 0, bytes_count); mandelbrot(N, data); fwrite( data, bytes_count, 1, stdout); fflush(stdout); free(data); return 0; }
rhs.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB BT code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" 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. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// #include "header.h" #include "timers.h" void compute_rhs() { int i, j, k, m; double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; //kai /* int k1,k2,k3,k4,k5,k6,k7,k8,k9,k10, k11; consistent_data(&k1, "int", 1); consistent_data(&k2, "int", 1); consistent_data(&k3, "int", 1); consistent_data(&k4, "int", 1); consistent_data(&k5, "int", 1); consistent_data(&k6, "int", 1); consistent_data(&k7, "int", 1); consistent_data(&k8, "int", 1); consistent_data(&k9, "int", 1); consistent_data(&k10, "int", 1); consistent_data(&k11, "int", 1); */ //kaii // double (*us_t)[grid_points[1]][grid_points[0]]= (double(*)[grid_points[1]][grid_points[0]])us; if (timeron) timer_start(t_rhs); #pragma omp parallel default(shared) private(i,j,k,m,rho_inv,uijk,up1,um1,\ vijk,vp1,vm1,wijk,wp1,wm1) { //--------------------------------------------------------------------- // compute the reciprocal of density, and the kinetic energy, // and the speed of sound. //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = k1+1; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { rho_inv = 1.0/u[k][j][i][0]; rho_i[k][j][i] = rho_inv; us[k][j][i] = u[k][j][i][1] * rho_inv; vs[k][j][i] = u[k][j][i][2] * rho_inv; ws[k][j][i] = u[k][j][i][3] * rho_inv; square[k][j][i] = 0.5* ( u[k][j][i][1]*u[k][j][i][1] + u[k][j][i][2]*u[k][j][i][2] + u[k][j][i][3]*u[k][j][i][3] ) * rho_inv; qs[k][j][i] = square[k][j][i] * rho_inv; } } //kai k1 = -1; } //--------------------------------------------------------------------- // copy the exact forcing term to the right hand side; because // this forcing term is known, we can store it on the whole grid // including the boundary //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = k2+1; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = forcing[k][j][i][m]; } } } //kai k2 = -1; } #pragma omp master if (timeron) timer_start(t_rhsx); //--------------------------------------------------------------------- // compute xi-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) nowait for (k = k3+1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { uijk = us[k][j][i]; up1 = us[k][j][i+1]; um1 = us[k][j][i-1]; rhs[k][j][i][0] = rhs[k][j][i][0] + dx1tx1 * (u[k][j][i+1][0] - 2.0*u[k][j][i][0] + u[k][j][i-1][0]) - tx2 * (u[k][j][i+1][1] - u[k][j][i-1][1]); rhs[k][j][i][1] = rhs[k][j][i][1] + dx2tx1 * (u[k][j][i+1][1] - 2.0*u[k][j][i][1] + u[k][j][i-1][1]) + xxcon2*con43 * (up1 - 2.0*uijk + um1) - tx2 * (u[k][j][i+1][1]*up1 - u[k][j][i-1][1]*um1 + (u[k][j][i+1][4]- square[k][j][i+1]- u[k][j][i-1][4]+ square[k][j][i-1])* c2); rhs[k][j][i][2] = rhs[k][j][i][2] + dx3tx1 * (u[k][j][i+1][2] - 2.0*u[k][j][i][2] + u[k][j][i-1][2]) + xxcon2 * (vs[k][j][i+1] - 2.0*vs[k][j][i] + vs[k][j][i-1]) - tx2 * (u[k][j][i+1][2]*up1 - u[k][j][i-1][2]*um1); rhs[k][j][i][3] = rhs[k][j][i][3] + dx4tx1 * (u[k][j][i+1][3] - 2.0*u[k][j][i][3] + u[k][j][i-1][3]) + xxcon2 * (ws[k][j][i+1] - 2.0*ws[k][j][i] + ws[k][j][i-1]) - tx2 * (u[k][j][i+1][3]*up1 - u[k][j][i-1][3]*um1); rhs[k][j][i][4] = rhs[k][j][i][4] + dx5tx1 * (u[k][j][i+1][4] - 2.0*u[k][j][i][4] + u[k][j][i-1][4]) + xxcon3 * (qs[k][j][i+1] - 2.0*qs[k][j][i] + qs[k][j][i-1]) + xxcon4 * (up1*up1 - 2.0*uijk*uijk + um1*um1) + xxcon5 * (u[k][j][i+1][4]*rho_i[k][j][i+1] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k][j][i-1][4]*rho_i[k][j][i-1]) - tx2 * ( (c1*u[k][j][i+1][4] - c2*square[k][j][i+1])*up1 - (c1*u[k][j][i-1][4] - c2*square[k][j][i-1])*um1 ); } } //--------------------------------------------------------------------- // add fourth order xi-direction dissipation //--------------------------------------------------------------------- for (j = 1; j <= grid_points[1]-2; j++) { i = 1; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m]); } i = 2; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m]); } } for (j = 1; j <= grid_points[1]-2; j++) { for (i = 3; i <= grid_points[0]-4; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] + u[k][j][i+2][m] ); } } } for (j = 1; j <= grid_points[1]-2; j++) { i = grid_points[0]-3; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.0*u[k][j][i-1][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j][i+1][m] ); } i = grid_points[0]-2; for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j][i-2][m] - 4.*u[k][j][i-1][m] + 5.*u[k][j][i][m] ); } } //kai k3 = 0; } #pragma omp master { if (timeron) timer_stop(t_rhsx); if (timeron) timer_start(t_rhsy); } //--------------------------------------------------------------------- // compute eta-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = k4+1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { vijk = vs[k][j][i]; vp1 = vs[k][j+1][i]; vm1 = vs[k][j-1][i]; rhs[k][j][i][0] = rhs[k][j][i][0] + dy1ty1 * (u[k][j+1][i][0] - 2.0*u[k][j][i][0] + u[k][j-1][i][0]) - ty2 * (u[k][j+1][i][2] - u[k][j-1][i][2]); rhs[k][j][i][1] = rhs[k][j][i][1] + dy2ty1 * (u[k][j+1][i][1] - 2.0*u[k][j][i][1] + u[k][j-1][i][1]) + yycon2 * (us[k][j+1][i] - 2.0*us[k][j][i] + us[k][j-1][i]) - ty2 * (u[k][j+1][i][1]*vp1 - u[k][j-1][i][1]*vm1); rhs[k][j][i][2] = rhs[k][j][i][2] + dy3ty1 * (u[k][j+1][i][2] - 2.0*u[k][j][i][2] + u[k][j-1][i][2]) + yycon2*con43 * (vp1 - 2.0*vijk + vm1) - ty2 * (u[k][j+1][i][2]*vp1 - u[k][j-1][i][2]*vm1 + (u[k][j+1][i][4] - square[k][j+1][i] - u[k][j-1][i][4] + square[k][j-1][i]) *c2); rhs[k][j][i][3] = rhs[k][j][i][3] + dy4ty1 * (u[k][j+1][i][3] - 2.0*u[k][j][i][3] + u[k][j-1][i][3]) + yycon2 * (ws[k][j+1][i] - 2.0*ws[k][j][i] + ws[k][j-1][i]) - ty2 * (u[k][j+1][i][3]*vp1 - u[k][j-1][i][3]*vm1); rhs[k][j][i][4] = rhs[k][j][i][4] + dy5ty1 * (u[k][j+1][i][4] - 2.0*u[k][j][i][4] + u[k][j-1][i][4]) + yycon3 * (qs[k][j+1][i] - 2.0*qs[k][j][i] + qs[k][j-1][i]) + yycon4 * (vp1*vp1 - 2.0*vijk*vijk + vm1*vm1) + yycon5 * (u[k][j+1][i][4]*rho_i[k][j+1][i] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k][j-1][i][4]*rho_i[k][j-1][i]) - ty2 * ((c1*u[k][j+1][i][4] - c2*square[k][j+1][i]) * vp1 - (c1*u[k][j-1][i][4] - c2*square[k][j-1][i]) * vm1); } } //--------------------------------------------------------------------- // add fourth order eta-direction dissipation //--------------------------------------------------------------------- j = 1; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m]); } } j = 2; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m]); } } for (j = 3; j <= grid_points[1]-4; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] + u[k][j+2][i][m] ); } } } j = grid_points[1]-3; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.0*u[k][j-1][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k][j+1][i][m] ); } } j = grid_points[1]-2; for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k][j-2][i][m] - 4.*u[k][j-1][i][m] + 5.*u[k][j][i][m] ); } } //kai k4 = 0; } #pragma omp master { if (timeron) timer_stop(t_rhsy); if (timeron) timer_start(t_rhsz); } //--------------------------------------------------------------------- // compute zeta-direction fluxes //--------------------------------------------------------------------- #pragma omp for schedule(static) for (k = k5+1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { wijk = ws[k][j][i]; wp1 = ws[k+1][j][i]; wm1 = ws[k-1][j][i]; rhs[k][j][i][0] = rhs[k][j][i][0] + dz1tz1 * (u[k+1][j][i][0] - 2.0*u[k][j][i][0] + u[k-1][j][i][0]) - tz2 * (u[k+1][j][i][3] - u[k-1][j][i][3]); rhs[k][j][i][1] = rhs[k][j][i][1] + dz2tz1 * (u[k+1][j][i][1] - 2.0*u[k][j][i][1] + u[k-1][j][i][1]) + zzcon2 * (us[k+1][j][i] - 2.0*us[k][j][i] + us[k-1][j][i]) - tz2 * (u[k+1][j][i][1]*wp1 - u[k-1][j][i][1]*wm1); rhs[k][j][i][2] = rhs[k][j][i][2] + dz3tz1 * (u[k+1][j][i][2] - 2.0*u[k][j][i][2] + u[k-1][j][i][2]) + zzcon2 * (vs[k+1][j][i] - 2.0*vs[k][j][i] + vs[k-1][j][i]) - tz2 * (u[k+1][j][i][2]*wp1 - u[k-1][j][i][2]*wm1); rhs[k][j][i][3] = rhs[k][j][i][3] + dz4tz1 * (u[k+1][j][i][3] - 2.0*u[k][j][i][3] + u[k-1][j][i][3]) + zzcon2*con43 * (wp1 - 2.0*wijk + wm1) - tz2 * (u[k+1][j][i][3]*wp1 - u[k-1][j][i][3]*wm1 + (u[k+1][j][i][4] - square[k+1][j][i] - u[k-1][j][i][4] + square[k-1][j][i]) *c2); rhs[k][j][i][4] = rhs[k][j][i][4] + dz5tz1 * (u[k+1][j][i][4] - 2.0*u[k][j][i][4] + u[k-1][j][i][4]) + zzcon3 * (qs[k+1][j][i] - 2.0*qs[k][j][i] + qs[k-1][j][i]) + zzcon4 * (wp1*wp1 - 2.0*wijk*wijk + wm1*wm1) + zzcon5 * (u[k+1][j][i][4]*rho_i[k+1][j][i] - 2.0*u[k][j][i][4]*rho_i[k][j][i] + u[k-1][j][i][4]*rho_i[k-1][j][i]) - tz2 * ( (c1*u[k+1][j][i][4] - c2*square[k+1][j][i])*wp1 - (c1*u[k-1][j][i][4] - c2*square[k-1][j][i])*wm1); } } //kai k5 = 0; } //--------------------------------------------------------------------- // add fourth order zeta-direction dissipation //--------------------------------------------------------------------- k = 1; #pragma omp for schedule(static) nowait for (j = k6+1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m]- dssp * ( 5.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m]); } } //kai k6 = 0; } k = 2; #pragma omp for schedule(static) nowait for (j = k7+1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m]); } } //kai k7 = 0; } #pragma omp for schedule(static) nowait for (k = k8+1; k <= grid_points[2]-4; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] + u[k+2][j][i][m] ); } } } //kai k8 = 2; } k = grid_points[2]-3; #pragma omp for schedule(static) nowait for (j = k9+1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.0*u[k-1][j][i][m] + 6.0*u[k][j][i][m] - 4.0*u[k+1][j][i][m] ); } } //kai k9 = 0; } k = grid_points[2]-2; #pragma omp for schedule(static) for (j = k10+1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * ( u[k-2][j][i][m] - 4.*u[k-1][j][i][m] + 5.*u[k][j][i][m] ); } } //kai k10 = 0; } #pragma omp master if (timeron) timer_stop(t_rhsz); #pragma omp for schedule(static) nowait for (k = k11+1; k <= grid_points[2]-2; k++) { for (j = 1; j <= grid_points[1]-2; j++) { for (i = 1; i <= grid_points[0]-2; i++) { for (m = 0; m < 5; m++) { rhs[k][j][i][m] = rhs[k][j][i][m] * dt; } } } //kai k11 = 0; } } //end parallel if (timeron) timer_stop(t_rhs); }
declare_simd_aarch64_sve.c
// REQUIRES: aarch64-registered-target // -fopemp and -fopenmp-simd behavior are expected to be the same // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve \ // RUN: -fopenmp -x c -emit-llvm %s -o - -femit-all-decls | FileCheck %s // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve \ // RUN: -fopenmp-simd -x c -emit-llvm %s -o - -femit-all-decls | FileCheck %s #pragma omp declare simd #pragma omp declare simd notinbranch #pragma omp declare simd simdlen(2) #pragma omp declare simd simdlen(4) #pragma omp declare simd simdlen(5) // not a multiple of 128-bits #pragma omp declare simd simdlen(6) #pragma omp declare simd simdlen(8) #pragma omp declare simd simdlen(32) #pragma omp declare simd simdlen(34) // requires more than 2048 bits double foo(float x); // CHECK-DAG: "_ZGVsM2v_foo" "_ZGVsM32v_foo" "_ZGVsM4v_foo" "_ZGVsM6v_foo" "_ZGVsM8v_foo" "_ZGVsMxv_foo" // CHECK-NOT: _ZGVsN // CHECK-NOT: _ZGVsM5v_foo // CHECK-NOT: _ZGVsM34v_foo // CHECK-NOT: foo void foo_loop(double *x, float *y, int N) { for (int i = 0; i < N; ++i) { x[i] = foo(y[i]); } } // test integers #pragma omp declare simd notinbranch char a01_fun(int x); // CHECK-DAG: _ZGVsMxv_a01_fun // CHECK-NOT: a01_fun static int *in; static char *out; void do_something() { *out = a01_fun(*in); }
_hypre_struct_mv.h
/*** DO NOT EDIT THIS FILE DIRECTLY (use 'headers' to generate) ***/ #ifndef hypre_STRUCT_MV_HEADER #define hypre_STRUCT_MV_HEADER #include <stdlib.h> #include <stdio.h> #include <math.h> #include "HYPRE_struct_mv.h" #include "_hypre_utilities.h" #if defined(HYPRE_USING_RAJA) /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_NEWBOXLOOP_HEADER #define HYPRE_NEWBOXLOOP_HEADER extern "C++" { #include <RAJA/RAJA.hpp> } using namespace RAJA; typedef struct hypre_Boxloop_struct { HYPRE_Int lsize0,lsize1,lsize2; HYPRE_Int strides0,strides1,strides2; HYPRE_Int bstart0,bstart1,bstart2; HYPRE_Int bsize0,bsize1,bsize2; } hypre_Boxloop; #if defined(HYPRE_USING_CUDA) /* RAJA with CUDA, running on device */ #define BLOCKSIZE 256 #define hypre_RAJA_DEVICE RAJA_DEVICE #define hypre_raja_exec_policy cuda_exec<BLOCKSIZE> /* #define hypre_raja_reduce_policy cuda_reduce_atomic<BLOCKSIZE> */ #define hypre_raja_reduce_policy cuda_reduce<BLOCKSIZE> #define hypre_fence() /* #define hypre_fence() \ cudaError err = cudaGetLastError();\ if ( cudaSuccess != err ) {\ printf("\n ERROR zypre_newBoxLoop: %s in %s(%d) function %s\n",cudaGetErrorString(err),__FILE__,__LINE__,__FUNCTION__); \ }\ hypre_CheckErrorDevice(cudaDeviceSynchronize()); */ #elif defined(HYPRE_USING_DEVICE_OPENMP) /* RAJA with OpenMP (>4.5), running on device */ //TODO #elif defined(HYPRE_USING_OPENMP) /* RAJA with OpenMP, running on host (CPU) */ #define hypre_RAJA_DEVICE #define hypre_raja_exec_policy omp_for_exec #define hypre_raja_reduce_policy omp_reduce #define hypre_fence() #else /* RAJA, running on host (CPU) */ #define hypre_RAJA_DEVICE #define hypre_raja_exec_policy seq_exec #define hypre_raja_reduce_policy seq_reduce #define hypre_fence() #endif /* #if defined(HYPRE_USING_CUDA) */ #define zypre_BoxLoopIncK(k,box,hypre__i) \ HYPRE_Int hypre_boxD##k = 1; \ HYPRE_Int hypre__i = 0; \ hypre__i += (hypre_IndexD(local_idx, 0)*box.strides0 + box.bstart0) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize0 + 1); \ hypre__i += (hypre_IndexD(local_idx, 1)*box.strides1 + box.bstart1) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize1 + 1); \ hypre__i += (hypre_IndexD(local_idx, 2)*box.strides2 + box.bstart2) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize2 + 1); \ #define zypre_newBoxLoopInit(ndim,loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int d = 0;d < ndim;d ++) \ hypre__tot *= loop_size[d]; #define zypre_newBoxLoopDeclare(box) \ hypre_Index local_idx; \ HYPRE_Int idx_local = idx; \ hypre_IndexD(local_idx, 0) = idx_local % box.lsize0; \ idx_local = idx_local / box.lsize0; \ hypre_IndexD(local_idx, 1) = idx_local % box.lsize1; \ idx_local = idx_local / box.lsize1; \ hypre_IndexD(local_idx, 2) = idx_local % box.lsize2; #define zypre_BoxLoopDataDeclareK(k,ndim,loop_size,dbox,start,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = start[0] - dbox->imin[0]; \ databox##k.bsize0 = dbox->imax[0]-dbox->imin[0]; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = start[1] - dbox->imin[1]; \ databox##k.bsize1 = dbox->imax[1]-dbox->imin[1]; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = start[2] - dbox->imin[2]; \ databox##k.bsize2 = dbox->imax[2]-dbox->imin[2]; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define zypre_newBoxLoop0Begin(ndim, loop_size) \ { \ zypre_newBoxLoopInit(ndim,loop_size); \ forall< hypre_raja_exec_policy >(RangeSegment(0, hypre__tot), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { #define zypre_newBoxLoop0End() \ }); \ hypre_fence(); \ } #define zypre_newBoxLoop1Begin(ndim, loop_size, \ dbox1, start1, stride1, i1) \ { \ zypre_newBoxLoopInit(ndim,loop_size); \ zypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ forall< hypre_raja_exec_policy >(RangeSegment(0, hypre__tot), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { \ zypre_newBoxLoopDeclare(databox1); \ zypre_BoxLoopIncK(1,databox1,i1); #define zypre_newBoxLoop1End(i1) \ }); \ hypre_fence(); \ } #define zypre_newBoxLoop2Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) \ { \ zypre_newBoxLoopInit(ndim,loop_size); \ zypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ zypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ forall< hypre_raja_exec_policy >(RangeSegment(0, hypre__tot), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { \ zypre_newBoxLoopDeclare(databox1); \ zypre_BoxLoopIncK(1,databox1,i1); \ zypre_BoxLoopIncK(2,databox2,i2); #define zypre_newBoxLoop2End(i1, i2) \ }); \ hypre_fence(); \ } #define zypre_newBoxLoop3Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ { \ zypre_newBoxLoopInit(ndim,loop_size); \ zypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ zypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ zypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ forall< hypre_raja_exec_policy >(RangeSegment(0, hypre__tot), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { \ zypre_newBoxLoopDeclare(databox1); \ zypre_BoxLoopIncK(1,databox1,i1); \ zypre_BoxLoopIncK(2,databox2,i2); \ zypre_BoxLoopIncK(3,databox3,i3); #define zypre_newBoxLoop3End(i1, i2, i3) \ }); \ hypre_fence(); \ } #define zypre_newBoxLoop4Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ { \ zypre_newBoxLoopInit(ndim,loop_size); \ zypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ zypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ zypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ zypre_BoxLoopDataDeclareK(4,ndim,loop_size,dbox4,start4,stride4); \ forall< hypre_raja_exec_policy >(RangeSegment(0, hypre__tot), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { \ zypre_newBoxLoopDeclare(databox1); \ zypre_BoxLoopIncK(1,databox1,i1); \ zypre_BoxLoopIncK(2,databox2,i2); \ zypre_BoxLoopIncK(3,databox3,i3); \ zypre_BoxLoopIncK(4,databox4,i4); #define zypre_newBoxLoop4End(i1, i2, i3, i4) \ }); \ hypre_fence(); \ } #define zypre_BasicBoxLoopDataDeclareK(k,ndim,loop_size,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = 0; \ databox##k.bsize0 = 0; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define zypre_newBasicBoxLoop2Begin(ndim, loop_size, \ stride1, i1, \ stride2, i2) \ { \ zypre_newBoxLoopInit(ndim,loop_size); \ zypre_BasicBoxLoopDataDeclareK(1,ndim,loop_size,stride1); \ zypre_BasicBoxLoopDataDeclareK(2,ndim,loop_size,stride2); \ forall< hypre_raja_exec_policy >(RangeSegment(0, hypre__tot), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { \ zypre_newBoxLoopDeclare(databox1); \ zypre_BoxLoopIncK(1,databox1,i1); \ zypre_BoxLoopIncK(2,databox2,i2); \ #define hypre_LoopBegin(size,idx) \ { \ forall< hypre_raja_exec_policy >(RangeSegment(0, size), [=] hypre_RAJA_DEVICE (HYPRE_Int idx) \ { #define hypre_LoopEnd() \ }); \ hypre_fence(); \ } #define zypre_newBoxLoopSetOneBlock() #define hypre_newBoxLoopGetIndex(index) \ index[0] = hypre_IndexD(local_idx, 0); \ index[1] = hypre_IndexD(local_idx, 1); \ index[2] = hypre_IndexD(local_idx, 2); #define hypre_BoxLoopGetIndex zypre_BoxLoopGetIndex #define hypre_BoxLoopSetOneBlock zypre_newBoxLoopSetOneBlock #define hypre_BoxLoopBlock() 0 #define hypre_BoxLoop0Begin zypre_newBoxLoop0Begin #define hypre_BoxLoop0For zypre_newBoxLoop0For #define hypre_BoxLoop0End zypre_newBoxLoop0End #define hypre_BoxLoop1Begin zypre_newBoxLoop1Begin #define hypre_BoxLoop1For zypre_newBoxLoop1For #define hypre_BoxLoop1End zypre_newBoxLoop1End #define hypre_BoxLoop2Begin zypre_newBoxLoop2Begin #define hypre_BoxLoop2For zypre_newBoxLoop2For #define hypre_BoxLoop2End zypre_newBoxLoop2End #define hypre_BoxLoop3Begin zypre_newBoxLoop3Begin #define hypre_BoxLoop3For zypre_newBoxLoop3For #define hypre_BoxLoop3End zypre_newBoxLoop3End #define hypre_BoxLoop4Begin zypre_newBoxLoop4Begin #define hypre_BoxLoop4For zypre_newBoxLoop4For #define hypre_BoxLoop4End zypre_newBoxLoop4End #define hypre_newBoxLoopInit zypre_newBoxLoopInit #define hypre_BasicBoxLoop2Begin zypre_newBasicBoxLoop2Begin /* Reduction */ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, reducesum) \ hypre_BoxLoop1Begin(ndim, loop_size, dbox1, start1, stride1, i1) #define hypre_BoxLoop1ReductionEnd(i1, reducesum) \ hypre_BoxLoop1End(i1) #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, reducesum) \ hypre_BoxLoop2Begin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) #define hypre_BoxLoop2ReductionEnd(i1, i2, reducesum) \ hypre_BoxLoop2End(i1, i2) #endif #elif defined(HYPRE_USING_KOKKOS) /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_NEWBOXLOOP_HEADER #define HYPRE_NEWBOXLOOP_HEADER extern "C++" { #include <Kokkos_Core.hpp> using namespace Kokkos; } #if defined( KOKKOS_HAVE_MPI ) #include <mpi.h> #endif typedef struct hypre_Boxloop_struct { HYPRE_Int lsize0,lsize1,lsize2; HYPRE_Int strides0,strides1,strides2; HYPRE_Int bstart0,bstart1,bstart2; HYPRE_Int bsize0,bsize1,bsize2; } hypre_Boxloop; #define hypre_fence() /* #define hypre_fence() \ cudaError err = cudaGetLastError(); \ if ( cudaSuccess != err ) { \ printf("\n ERROR hypre_newBoxLoop: %s in %s(%d) function %s\n", cudaGetErrorString(err),__FILE__,__LINE__,__FUNCTION__); \ } \ hypre_CheckErrorDevice(cudaDeviceSynchronize()); */ #define hypre_newBoxLoopInit(ndim,loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int d = 0;d < ndim;d ++) \ hypre__tot *= loop_size[d]; #define hypre_BoxLoopIncK(k,box,hypre__i) \ HYPRE_Int hypre_boxD##k = 1; \ HYPRE_Int hypre__i = 0; \ hypre__i += (hypre_IndexD(local_idx, 0)*box.strides0 + box.bstart0) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize0 + 1); \ hypre__i += (hypre_IndexD(local_idx, 1)*box.strides1 + box.bstart1) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize1 + 1); \ hypre__i += (hypre_IndexD(local_idx, 2)*box.strides2 + box.bstart2) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize2 + 1); \ #define hypre_newBoxLoopDeclare(box) \ hypre_Index local_idx; \ HYPRE_Int idx_local = idx; \ hypre_IndexD(local_idx, 0) = idx_local % box.lsize0; \ idx_local = idx_local / box.lsize0; \ hypre_IndexD(local_idx, 1) = idx_local % box.lsize1; \ idx_local = idx_local / box.lsize1; \ hypre_IndexD(local_idx, 2) = idx_local % box.lsize2; #define hypre_BoxLoopDataDeclareK(k,ndim,loop_size,dbox,start,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = start[0] - dbox->imin[0]; \ databox##k.bsize0 = dbox->imax[0]-dbox->imin[0]; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = start[1] - dbox->imin[1]; \ databox##k.bsize1 = dbox->imax[1]-dbox->imin[1]; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = start[2] - dbox->imin[2]; \ databox##k.bsize2 = dbox->imax[2]-dbox->imin[2]; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define hypre_newBoxLoop0Begin(ndim, loop_size) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ Kokkos::parallel_for (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx) \ { #define hypre_newBoxLoop0End(i1) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop1Begin(ndim, loop_size, \ dbox1, start1, stride1, i1) \ { \ hypre_newBoxLoopInit(ndim,loop_size) \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ Kokkos::parallel_for (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); #define hypre_newBoxLoop1End(i1) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop2Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ Kokkos::parallel_for (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1) \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); #define hypre_newBoxLoop2End(i1, i2) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop3Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ hypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ Kokkos::parallel_for (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ hypre_BoxLoopIncK(3,databox3,i3); #define hypre_newBoxLoop3End(i1, i2, i3) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop4Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ hypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ hypre_BoxLoopDataDeclareK(4,ndim,loop_size,dbox4,start4,stride4); \ Kokkos::parallel_for (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ hypre_BoxLoopIncK(3,databox3,i3); \ hypre_BoxLoopIncK(4,databox4,i4); #define hypre_newBoxLoop4End(i1, i2, i3, i4) \ }); \ hypre_fence(); \ } #define hypre_BasicBoxLoopDataDeclareK(k,ndim,loop_size,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = 0; \ databox##k.bsize0 = 0; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define hypre_newBasicBoxLoop2Begin(ndim, loop_size, \ stride1, i1, \ stride2, i2) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BasicBoxLoopDataDeclareK(1,ndim,loop_size,stride1); \ hypre_BasicBoxLoopDataDeclareK(2,ndim,loop_size,stride2); \ Kokkos::parallel_for (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ HYPRE_BOX_REDUCTION) \ { \ HYPRE_Real __hypre_sum_tmp = HYPRE_BOX_REDUCTION; \ HYPRE_BOX_REDUCTION = 0.0; \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ Kokkos::parallel_reduce (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx, \ HYPRE_Real &HYPRE_BOX_REDUCTION) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ #define hypre_BoxLoop1ReductionEnd(i1, HYPRE_BOX_REDUCTION) \ }, HYPRE_BOX_REDUCTION); \ hypre_fence(); \ HYPRE_BOX_REDUCTION += __hypre_sum_tmp; \ } #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ HYPRE_BOX_REDUCTION) \ { \ HYPRE_Real __hypre_sum_tmp = HYPRE_BOX_REDUCTION; \ HYPRE_BOX_REDUCTION = 0.0; \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ Kokkos::parallel_reduce (hypre__tot, KOKKOS_LAMBDA (HYPRE_Int idx, \ HYPRE_Real &HYPRE_BOX_REDUCTION) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ #define hypre_BoxLoop2ReductionEnd(i1, i2, HYPRE_BOX_REDUCTION) \ }, HYPRE_BOX_REDUCTION); \ hypre_fence(); \ HYPRE_BOX_REDUCTION += __hypre_sum_tmp; \ } #define hypre_LoopBegin(size,idx) \ { \ Kokkos::parallel_for(size, KOKKOS_LAMBDA (HYPRE_Int idx) \ { #define hypre_LoopEnd() \ }); \ hypre_fence(); \ } /* extern "C++" { struct ColumnSums { typedef HYPRE_Real value_type[]; typedef View<HYPRE_Real**>::size_type size_type; size_type value_count; View<HYPRE_Real**> X_; ColumnSums(const View<HYPRE_Real**>& X):value_count(X.dimension_1()),X_(X){} KOKKOS_INLINE_FUNCTION void operator()(const size_type i,value_type sum) const { for (size_type j = 0;j < value_count;j++) { sum[j] += X_(i,j); } } KOKKOS_INLINE_FUNCTION void join (volatile value_type dst,volatile value_type src) const { for (size_type j= 0;j < value_count;j++) { dst[j] +=src[j]; } } KOKKOS_INLINE_FUNCTION void init(value_type sum) const { for (size_type j= 0;j < value_count;j++) { sum[j] += 0.0; } } }; } */ #define hypre_newBoxLoopSetOneBlock() #define hypre_newBoxLoopGetIndex(index)\ index[0] = hypre_IndexD(local_idx, 0); index[1] = hypre_IndexD(local_idx, 1); index[2] = hypre_IndexD(local_idx, 2); #define hypre_BoxLoopGetIndex zypre_BoxLoopGetIndex #define hypre_BoxLoopSetOneBlock hypre_newBoxLoopSetOneBlock #define hypre_BoxLoopBlock() 0 #define hypre_BoxLoop0Begin hypre_newBoxLoop0Begin #define hypre_BoxLoop0For hypre_newBoxLoop0For #define hypre_BoxLoop0End hypre_newBoxLoop0End #define hypre_BoxLoop1Begin hypre_newBoxLoop1Begin #define hypre_BoxLoop1For hypre_newBoxLoop1For #define hypre_BoxLoop1End hypre_newBoxLoop1End #define hypre_BoxLoop2Begin hypre_newBoxLoop2Begin #define hypre_BoxLoop2For hypre_newBoxLoop2For #define hypre_BoxLoop2End hypre_newBoxLoop2End #define hypre_BoxLoop3Begin hypre_newBoxLoop3Begin #define hypre_BoxLoop3For hypre_newBoxLoop3For #define hypre_BoxLoop3End hypre_newBoxLoop3End #define hypre_BoxLoop4Begin hypre_newBoxLoop4Begin #define hypre_BoxLoop4For hypre_newBoxLoop4For #define hypre_BoxLoop4End hypre_newBoxLoop4End #define hypre_BasicBoxLoop2Begin hypre_newBasicBoxLoop2Begin #endif #elif defined(HYPRE_USING_CUDA) /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_NEWBOXLOOP_HEADER #define HYPRE_NEWBOXLOOP_HEADER #include <cuda.h> #include <cuda_runtime.h> #ifdef HYPRE_USING_OPENMP #include <omp.h> #endif #define HYPRE_LAMBDA [=] __host__ __device__ #define BLOCKSIZE 512 typedef struct hypre_Boxloop_struct { HYPRE_Int lsize0,lsize1,lsize2; HYPRE_Int strides0,strides1,strides2; HYPRE_Int bstart0,bstart1,bstart2; HYPRE_Int bsize0,bsize1,bsize2; } hypre_Boxloop; #if 1 #define hypre_fence() /*printf("\n hypre_newBoxLoop in %s(%d) function %s\n",__FILE__,__LINE__,__FUNCTION__);*/ #else #define hypre_fence() \ { \ cudaError err = cudaGetLastError(); \ if ( cudaSuccess != err ) \ { \ printf("\n ERROR hypre_newBoxLoop: %s in %s(%d) function %s\n",cudaGetErrorString(err),__FILE__,__LINE__,__FUNCTION__); \ /* HYPRE_Int *p = NULL; *p = 1; */ \ } \ hypre_CheckErrorDevice(cudaDeviceSynchronize()); \ } #endif /* #define hypre_reduce_policy cuda_reduce<BLOCKSIZE> */ extern "C++" { template <typename LOOP_BODY> __global__ void forall_kernel(LOOP_BODY loop_body, HYPRE_Int length) { HYPRE_Int idx = blockDim.x * blockIdx.x + threadIdx.x; if (idx < length) { loop_body(idx); } } template<typename LOOP_BODY> void BoxLoopforall(HYPRE_Int policy, HYPRE_Int length, LOOP_BODY loop_body) { if (policy == HYPRE_MEMORY_HOST) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (HYPRE_Int idx = 0; idx < length; idx++) { loop_body(idx); } } else if (policy == HYPRE_MEMORY_DEVICE) { HYPRE_Int gridSize = (length + BLOCKSIZE - 1) / BLOCKSIZE; const dim3 gDim(gridSize), bDim(BLOCKSIZE); HYPRE_CUDA_LAUNCH( forall_kernel, gDim, bDim, loop_body, length ); } else if (policy == 2) { } } template <typename LOOP_BODY> __global__ void reductionforall_kernel(LOOP_BODY ReductionLoop, HYPRE_Int length) { ReductionLoop(blockDim.x*blockIdx.x+threadIdx.x, blockDim.x*gridDim.x, length); } template<typename LOOP_BODY> void ReductionBoxLoopforall(HYPRE_Int policy, HYPRE_Int length, LOOP_BODY ReductionLoop) { if (length <= 0) { return; } if (policy == HYPRE_MEMORY_HOST) { } else if (policy == HYPRE_MEMORY_DEVICE) { HYPRE_Int gridSize = (length + BLOCKSIZE - 1) / BLOCKSIZE; gridSize = hypre_min(gridSize, 1024); /* hypre_printf("length= %d, blocksize = %d, gridsize = %d\n", length, BLOCKSIZE, gridSize); */ const dim3 gDim(gridSize), bDim(BLOCKSIZE); HYPRE_CUDA_LAUNCH( reductionforall_kernel, gDim, bDim, ReductionLoop, length ); } } } #define hypre_BoxLoopIncK(k,box,hypre__i) \ HYPRE_Int hypre_boxD##k = 1; \ HYPRE_Int hypre__i = 0; \ hypre__i += (hypre_IndexD(local_idx, 0)*box.strides0 + box.bstart0) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize0 + 1); \ hypre__i += (hypre_IndexD(local_idx, 1)*box.strides1 + box.bstart1) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize1 + 1); \ hypre__i += (hypre_IndexD(local_idx, 2)*box.strides2 + box.bstart2) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize2 + 1); #define hypre_newBoxLoopInit(ndim,loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int hypre_d = 0;hypre_d < ndim;hypre_d ++) \ hypre__tot *= loop_size[hypre_d]; #define hypre_BasicBoxLoopInit(ndim,loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int hypre_d = 0;hypre_d < ndim;hypre_d ++) \ hypre__tot *= loop_size[hypre_d]; \ #define hypre_newBoxLoopDeclare(box) \ hypre_Index local_idx; \ HYPRE_Int idx_local = idx; \ hypre_IndexD(local_idx, 0) = idx_local % box.lsize0; \ idx_local = idx_local / box.lsize0; \ hypre_IndexD(local_idx, 1) = idx_local % box.lsize1; \ idx_local = idx_local / box.lsize1; \ hypre_IndexD(local_idx, 2) = idx_local % box.lsize2; \ #define hypre_newBoxLoop0Begin(ndim, loop_size) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { #define hypre_newBoxLoop0End() \ }); \ hypre_fence(); \ } #define hypre_BoxLoopDataDeclareK(k,ndim,loop_size,dbox,start,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = start[0] - dbox->imin[0]; \ databox##k.bsize0 = dbox->imax[0]-dbox->imin[0]; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = start[1] - dbox->imin[1]; \ databox##k.bsize1 = dbox->imax[1]-dbox->imin[1]; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = start[2] - dbox->imin[2]; \ databox##k.bsize2 = dbox->imax[2]-dbox->imin[2]; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define hypre_newBoxLoop1Begin(ndim, loop_size, \ dbox1, start1, stride1, i1) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); #define hypre_newBoxLoop1End(i1) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop2Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); #define hypre_newBoxLoop2End(i1, i2) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop3Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ hypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ hypre_BoxLoopIncK(3,databox3,i3); #define hypre_newBoxLoop3End(i1, i2,i3) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop4Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ hypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ hypre_BoxLoopDataDeclareK(4,ndim,loop_size,dbox4,start4,stride4); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ hypre_BoxLoopIncK(3,databox3,i3); \ hypre_BoxLoopIncK(4,databox4,i4); #define hypre_newBoxLoop4End(i1, i2, i3, i4) \ }); \ hypre_fence(); \ } #define zypre_BasicBoxLoopDataDeclareK(k,ndim,loop_size,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = 0; \ databox##k.bsize0 = 0; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define zypre_newBasicBoxLoop1Begin(ndim, loop_size, \ stride1, i1) \ { \ hypre_BasicBoxLoopInit(ndim,loop_size); \ zypre_BasicBoxLoopDataDeclareK(1,ndim,loop_size,stride1); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ #define zypre_newBasicBoxLoop2Begin(ndim, loop_size, \ stride1, i1, \ stride2, i2) \ { \ hypre_BasicBoxLoopInit(ndim,loop_size); \ zypre_BasicBoxLoopDataDeclareK(1,ndim,loop_size,stride1); \ zypre_BasicBoxLoopDataDeclareK(2,ndim,loop_size,stride2); \ BoxLoopforall(hypre_exec_policy,hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ #define hypre_LoopBegin(size,idx) \ { \ BoxLoopforall(hypre_exec_policy,size,HYPRE_LAMBDA (HYPRE_Int idx) \ { #define hypre_LoopEnd() \ }); \ hypre_fence(); \ } #define hypre_newBoxLoopGetIndex(index) \ index[0] = hypre_IndexD(local_idx, 0); index[1] = hypre_IndexD(local_idx, 1); index[2] = hypre_IndexD(local_idx, 2); #define hypre_BoxLoopGetIndex zypre_BoxLoopGetIndex #define hypre_BoxLoopSetOneBlock() ; #define hypre_BoxLoopBlock() 0 #define hypre_BoxLoop0Begin hypre_newBoxLoop0Begin #define hypre_BoxLoop0For hypre_newBoxLoop0For #define hypre_BoxLoop0End hypre_newBoxLoop0End #define hypre_BoxLoop1Begin hypre_newBoxLoop1Begin #define hypre_BoxLoop1For hypre_newBoxLoop1For #define hypre_BoxLoop1End hypre_newBoxLoop1End #define hypre_BoxLoop2Begin hypre_newBoxLoop2Begin #define hypre_BoxLoop2For hypre_newBoxLoop2For #define hypre_BoxLoop2End hypre_newBoxLoop2End #define hypre_BoxLoop3Begin hypre_newBoxLoop3Begin #define hypre_BoxLoop3For hypre_newBoxLoop3For #define hypre_BoxLoop3End hypre_newBoxLoop3End #define hypre_BoxLoop4Begin hypre_newBoxLoop4Begin #define hypre_BoxLoop4For hypre_newBoxLoop4For #define hypre_BoxLoop4End hypre_newBoxLoop4End #define hypre_BasicBoxLoop1Begin zypre_newBasicBoxLoop1Begin #define hypre_BasicBoxLoop2Begin zypre_newBasicBoxLoop2Begin /* Reduction BoxLoop1*/ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ reducesum) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ reducesum.nblocks = hypre_min( (hypre__tot+BLOCKSIZE-1)/BLOCKSIZE, 1024 ); \ ReductionBoxLoopforall(hypre_exec_policy, hypre__tot, \ HYPRE_LAMBDA (HYPRE_Int tid, HYPRE_Int nthreads, \ HYPRE_Int len) \ { \ for (HYPRE_Int idx = tid; \ idx < len; \ idx += nthreads) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); #define hypre_BoxLoop1ReductionEnd(i1, reducesum) \ } \ reducesum.BlockReduce(); \ }); \ hypre_fence(); \ } /* Reduction BoxLoop2 */ #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ reducesum) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ reducesum.nblocks = hypre_min( (hypre__tot+BLOCKSIZE-1)/BLOCKSIZE, 1024 ); \ ReductionBoxLoopforall(hypre_exec_policy, hypre__tot, \ HYPRE_LAMBDA (HYPRE_Int tid, HYPRE_Int nthreads, \ HYPRE_Int len) \ { \ for (HYPRE_Int idx = tid; \ idx < len; \ idx += nthreads) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); #define hypre_BoxLoop2ReductionEnd(i1, i2, reducesum) \ } \ reducesum.BlockReduce(); \ }); \ hypre_fence(); \ } #endif #elif defined(HYPRE_USING_DEVICE_OPENMP) /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_NEWBOXLOOP_HEADER #define HYPRE_NEWBOXLOOP_HEADER #include "omp.h" /* concatenation: */ #define HYPRE_CONCAT2(x, y) x ## _ ## y #define HYPRE_XCONCAT2(x, y) HYPRE_CONCAT2(x, y) #define HYPRE_CONCAT3(x, y, z) x ## _ ## y ## _ ## z #define HYPRE_XCONCAT3(x, y, z) HYPRE_CONCAT3(x, y, z) /* if use OMP 4.5 default team size and number of teams */ #define AUTO_OMP_TEAM #ifndef AUTO_OMP_TEAM /* omp team size (aka. gpu block size) */ #define hypre_gpu_block_size 512 /* the max number of omp teams */ #define hypre_max_num_blocks 1000000 #endif //#define HYPRE_BOXLOOP_ENTRY_PRINT hypre_printf("%s %s %d\n", __FILE__, __func__, __LINE__); #define HYPRE_BOXLOOP_ENTRY_PRINT /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - BOX LOOPS [TEAM DISTRIBUTE VERSION] !!! NOTE: THIS CODE ONLY WORKS FOR DIM <= 3 !!! * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ /* #define hypre_BoxLoop0For() #define hypre_BoxLoop1For(i1) #define hypre_BoxLoop2For(i1, i2) #define hypre_BoxLoop3For(i1, i2, i3) #define hypre_BoxLoop4For(i1, i2, i3, i4) */ #define hypre_BoxLoopGetIndex zypre_BoxLoopGetIndex #define hypre_BoxLoopSetOneBlock() ; #define hypre_BoxLoopBlock() 0 #define hypre_BoxLoop0Begin zypre_omp4_dist_BoxLoop0Begin #define hypre_BoxLoop0End zypre_omp4_dist_BoxLoopEnd #define hypre_BoxLoop1Begin zypre_omp4_dist_BoxLoop1Begin #define hypre_BoxLoop1End zypre_omp4_dist_BoxLoopEnd #define hypre_BasicBoxLoop2Begin zypre_omp4_dist_BoxLoop2_v2_Begin #define hypre_BoxLoop2Begin zypre_omp4_dist_BoxLoop2Begin #define hypre_BoxLoop2End zypre_omp4_dist_BoxLoopEnd #define hypre_BoxLoop3Begin zypre_omp4_dist_BoxLoop3Begin #if 0 #define hypre_BoxLoop3_SAME_STRIDE_Begin zypre_omp4_dist_BoxLoop3_SAME_STRIDE_Begin #endif #define hypre_BoxLoop3End zypre_omp4_dist_BoxLoopEnd #define hypre_BoxLoop4Begin zypre_omp4_dist_BoxLoop4Begin #define hypre_BoxLoop4End zypre_omp4_dist_BoxLoopEnd #define hypre_LoopBegin zypre_LoopBegin #define hypre_LoopEnd zypre_omp4_dist_BoxLoopEnd /* Look for more in struct_ls/red_black_gs.h" */ #define zypre_omp4_dist_BoxLoopEnd(...) \ }\ /*cudaDeviceSynchronize();*/ \ } #define HYPRE_BOX_REDUCTION /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * host code: declare variables used in the box loop * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopDeclareInit_0(ndim, loop_size) \ HYPRE_Int hypre__ndim = ndim, hypre__tot = 1; \ /* HYPRE_Int hypre__thread; */ \ /* loop size */ \ HYPRE_Int hypre__loop_size_0, hypre__loop_size_1, hypre__loop_size_2; \ if (hypre__ndim > 0) { hypre__loop_size_0 = loop_size[0]; hypre__tot *= hypre__loop_size_0; } \ if (hypre__ndim > 1) { hypre__loop_size_1 = loop_size[1]; hypre__tot *= hypre__loop_size_1; } \ if (hypre__ndim > 2) { hypre__loop_size_2 = loop_size[2]; hypre__tot *= hypre__loop_size_2; } #ifdef AUTO_OMP_TEAM #define TEAM_CLAUSE #define zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) zypre_omp4_BoxLoopDeclareInit_0(ndim, loop_size) #else #define TEAM_CLAUSE num_teams(num_blocks) thread_limit(block_size) #define zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) zypre_omp4_BoxLoopDeclareInit_0(ndim, loop_size) \ /* GPU block numbers and dimensions */ \ HYPRE_Int block_size = hypre_gpu_block_size; \ HYPRE_Int num_blocks = hypre_min(hypre_max_num_blocks, (hypre__tot + hypre_gpu_block_size - 1) / hypre_gpu_block_size); #endif /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * host code: declare and initialize variables for box k * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxKDeclareInitBody(j, k, startk, dboxk, stridek) \ HYPRE_XCONCAT3(hypre__stride,j,k) = stridek[j]; \ /* precompute some entities used in the parallel for loop */ \ HYPRE_XCONCAT3(hypre__box_start_imin,j,k) = startk[j] - dboxk->imin[j]; \ HYPRE_XCONCAT3(hypre__box_imax_imin,j,k) = dboxk->imax[j] - dboxk->imin[j] + 1; #define zypre_omp4_BoxKDeclareInit(k, startk, dboxk, stridek)\ /* start - imin */ \ HYPRE_Int HYPRE_XCONCAT3(hypre__box_start_imin,0,k), HYPRE_XCONCAT3(hypre__box_start_imin,1,k), HYPRE_XCONCAT3(hypre__box_start_imin,2,k); \ /* imax - imin + 1 */ \ HYPRE_Int HYPRE_XCONCAT3(hypre__box_imax_imin,0,k), HYPRE_XCONCAT3(hypre__box_imax_imin,1,k), HYPRE_XCONCAT3(hypre__box_imax_imin,2,k); \ /* stride */ \ HYPRE_Int HYPRE_XCONCAT3(hypre__stride,0,k), HYPRE_XCONCAT3(hypre__stride,1,k), HYPRE_XCONCAT3(hypre__stride,2,k); \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxKDeclareInitBody(0, k, startk, dboxk, stridek) } \ if (hypre__ndim > 1) { zypre_omp4_BoxKDeclareInitBody(1, k, startk, dboxk, stridek) } \ if (hypre__ndim > 2) { zypre_omp4_BoxKDeclareInitBody(2, k, startk, dboxk, stridek) } \ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * map clause * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define MAP_CLAUSE0 #define MAP_CLAUSE1 #define MAP_CLAUSE2 #define MAP_CLAUSE3 #define MAP_CLAUSE4 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * if clause * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define IF_CLAUSE if (hypre__global_offload && hypre__tot > 0) //#define IF_CLAUSE /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * is_device_ptr clause * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #if defined(HYPRE_DEVICE_OPENMP_ALLOC) #define IS_DEVICE_CLAUSE DEVICE_VAR #else #define IS_DEVICE_CLAUSE #endif /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * device code for BoxLoop 1, set i1 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopSet1Body(j, i1) \ /* coord in dimension j */ \ hypre__i = hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j); \ /* once */ \ hypre__i_1 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,1) + HYPRE_XCONCAT3(hypre__box_start_imin,j,1);\ /* once */ \ i1 += hypre__i_1 * hypre__I_1; \ /* once */ \ hypre__I_1 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,1); \ /* */ \ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); \ /* !!! special for BoxLoop1: save the 3-D id */ \ /* HYPRE_XCONCAT2(hypre__id,j) = hypre__i; */ #define zypre_omp4_BoxLoopSet1(i1) \ HYPRE_Int hypre__I_1, hypre__i, hypre__i_1, hypre__J, i1, idx; \ /* HYPRE_Int hypre__id_0, hypre__id_1, hypre__id_2; */ \ hypre__I_1 = 1; idx = hypre__J = hypre__thread; i1 = 0; \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet1Body(0, i1) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet1Body(1, i1) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet1Body(2, i1) } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * device code for BoxLoop 2, set i1, i2 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopSet2Body(j, i1, i2) \ /* */ \ hypre__i = hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j); \ /* twice */ \ hypre__i_1 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,1) + HYPRE_XCONCAT3(hypre__box_start_imin,j,1);\ hypre__i_2 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,2) + HYPRE_XCONCAT3(hypre__box_start_imin,j,2);\ /* twice */ \ i1 += hypre__i_1 * hypre__I_1; \ i2 += hypre__i_2 * hypre__I_2; \ /* twice */ \ hypre__I_1 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,1); \ hypre__I_2 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,2); \ /* */ \ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); #define zypre_omp4_BoxLoopSet2(i1, i2) \ HYPRE_Int hypre__I_1, hypre__I_2, hypre__i, hypre__i_1, hypre__i_2, hypre__J, i1, i2; \ hypre__I_1 = hypre__I_2 = 1; hypre__J = hypre__thread; i1 = i2 = 0; \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet2Body(0, i1, i2) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet2Body(1, i1, i2) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet2Body(2, i1, i2) } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * device code for BoxLoop 3, set i1, i2, i3 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopSet3Body(j, i1, i2, i3) \ /* */ \ hypre__i = hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j); \ /* 3 times */ \ hypre__i_1 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,1) + HYPRE_XCONCAT3(hypre__box_start_imin,j,1);\ hypre__i_2 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,2) + HYPRE_XCONCAT3(hypre__box_start_imin,j,2);\ hypre__i_3 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,3) + HYPRE_XCONCAT3(hypre__box_start_imin,j,3);\ /* 3 times */ \ i1 += hypre__i_1 * hypre__I_1; \ i2 += hypre__i_2 * hypre__I_2; \ i3 += hypre__i_3 * hypre__I_3; \ /* 3 times */ \ hypre__I_1 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,1); \ hypre__I_2 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,2); \ hypre__I_3 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,3); \ /* */ \ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); #define zypre_omp4_BoxLoopSet3(i1, i2, i3) \ HYPRE_Int hypre__I_1, hypre__I_2, hypre__I_3, hypre__i, hypre__i_1, hypre__i_2, hypre__i_3, hypre__J, i1, i2, i3; \ hypre__I_1 = hypre__I_2 = hypre__I_3 = 1; hypre__J = hypre__thread; i1 = i2 = i3 = 0; \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet3Body(0, i1, i2, i3) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet3Body(1, i1, i2, i3) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet3Body(2, i1, i2, i3) } #if 0 /* - - - - - special Box 3: XXX */ #define zypre_omp4_BoxLoopSet3_SAME_STRIDE_Body(j, i1, i2, i3) \ /* */ \ hypre__i = (hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j)) * HYPRE_XCONCAT3(hypre__stride,j,1); \ /* 3 times */ \ hypre__i_1 = hypre__i + HYPRE_XCONCAT3(hypre__box_start_imin,j,1);\ hypre__i_2 = hypre__i + HYPRE_XCONCAT3(hypre__box_start_imin,j,2);\ hypre__i_3 = hypre__i + HYPRE_XCONCAT3(hypre__box_start_imin,j,3);\ /* 3 times */ \ i1 += hypre__i_1 * hypre__I_1; \ i2 += hypre__i_2 * hypre__I_2; \ i3 += hypre__i_3 * hypre__I_3; \ /* 3 times */ \ hypre__I_1 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,1); \ hypre__I_2 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,2); \ hypre__I_3 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,3); \ /* */ \ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); #define zypre_omp4_BoxLoopSet3_SAME_STRIDE(i1, i2, o2, i3) \ HYPRE_Int hypre__I_1, hypre__I_2, hypre__I_3, hypre__i, hypre__i_1, hypre__i_2, hypre__i_3, hypre__J; \ hypre__I_1 = hypre__I_2 = hypre__I_3 = 1; hypre__J = hypre__thread; i1 = i3 = 0; i2 = o2;\ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet3_SAME_STRIDE_Body(0, i1, i2, i3) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet3_SAME_STRIDE_Body(1, i1, i2, i3) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet3_SAME_STRIDE_Body(2, i1, i2, i3) } #endif /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * device code for BoxLoop 4, set i1, i2, i3, i4 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopSet4Body(j, i1, i2, i3, i4) \ /* */ \ hypre__i = hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j); \ /* 4 times */ \ hypre__i_1 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,1) + HYPRE_XCONCAT3(hypre__box_start_imin,j,1);\ hypre__i_2 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,2) + HYPRE_XCONCAT3(hypre__box_start_imin,j,2);\ hypre__i_3 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,3) + HYPRE_XCONCAT3(hypre__box_start_imin,j,3);\ hypre__i_4 = hypre__i * HYPRE_XCONCAT3(hypre__stride,j,4) + HYPRE_XCONCAT3(hypre__box_start_imin,j,4);\ /* 4 times */ \ i1 += hypre__i_1 * hypre__I_1; \ i2 += hypre__i_2 * hypre__I_2; \ i3 += hypre__i_3 * hypre__I_3; \ i4 += hypre__i_4 * hypre__I_4; \ /* 4 times */ \ hypre__I_1 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,1); \ hypre__I_2 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,2); \ hypre__I_3 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,3); \ hypre__I_4 *= HYPRE_XCONCAT3(hypre__box_imax_imin,j,4); \ /* */ \ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); #define zypre_omp4_BoxLoopSet4(i1, i2, i3, i4) \ HYPRE_Int hypre__I_1, hypre__I_2, hypre__I_3, hypre__I_4, hypre__i, hypre__i_1, hypre__i_2, hypre__i_3, hypre__i_4, hypre__J, i1, i2, i3, i4; \ hypre__I_1 = hypre__I_2 = hypre__I_3 = hypre__I_4 = 1; hypre__J = hypre__thread; i1 = i2 = i3 = i4 = 0; \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet4Body(0, i1, i2, i3, i4) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet4Body(1, i1, i2, i3, i4) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet4Body(2, i1, i2, i3, i4) } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 0 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop0Begin(ndim, loop_size) \ {\ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE0 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 1 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop1Begin(ndim, loop_size, dbox1, start1, stride1, i1) \ {\ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE1 IS_DEVICE_CLAUSE HYPRE_BOX_REDUCTION TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet1(i1) /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 2 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop2Begin(ndim, loop_size, dbox1, start1, stride1, i1, dbox2, start2, stride2, i2) \ {\ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ zypre_omp4_BoxKDeclareInit(2, start2, dbox2, stride2) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE2 IS_DEVICE_CLAUSE HYPRE_BOX_REDUCTION TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet2(i1, i2) /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 3 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop3Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ {\ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ zypre_omp4_BoxKDeclareInit(2, start2, dbox2, stride2) \ zypre_omp4_BoxKDeclareInit(3, start3, dbox3, stride3) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE3 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet3(i1, i2, i3) #if 0 #define zypre_omp4_dist_BoxLoop3_SAME_STRIDE_Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, o2, \ dbox3, start3, stride3, i3) \ {\ /* host code: */ \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ zypre_omp4_BoxKDeclareInit(2, start2, dbox2, stride2) \ zypre_omp4_BoxKDeclareInit(3, start3, dbox3, stride3) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE3 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet3_SAME_STRIDE(i1, i2, o2, i3) #endif /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 4 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop4Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ {\ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ zypre_omp4_BoxKDeclareInit(2, start2, dbox2, stride2) \ zypre_omp4_BoxKDeclareInit(3, start3, dbox3, stride3) \ zypre_omp4_BoxKDeclareInit(4, start4, dbox4, stride4) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE4 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet4(i1, i2, i3, i4) #if 0 /* no longer needed, use the above BoxLoop's for reductions */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 1 reduction * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_Red_BoxLoop1Begin(ndim, loop_size, dbox1, start1, stride1, i1, xsum) \ {\ /* host code: */ \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE1 map(tofrom: xsum) reduction(+:xsum) TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet1(i1) /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * BoxLoop 2 reduction * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_Red_BoxLoop2Begin(ndim, loop_size, dbox1, start1, stride1, i1, dbox2, start2, stride2, i2, xsum) \ {\ /* host code: */ \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit(1, start1, dbox1, stride1) \ zypre_omp4_BoxKDeclareInit(2, start2, dbox2, stride2) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE2 map(tofrom: xsum) reduction(+:xsum) TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet2(i1, i2) #endif /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * v2 * host code: declare and initialize variables for box k * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxKDeclareInit_v2(k, stridek)\ /* stridek[0,1,2] */ \ HYPRE_Int HYPRE_XCONCAT3(hypre__stride,0,k), HYPRE_XCONCAT3(hypre__stride,1,k), HYPRE_XCONCAT3(hypre__stride,2,k); \ /*if (hypre__ndim > 0)*/ { HYPRE_XCONCAT3(hypre__stride,0,k) = stridek[0]; } \ if (hypre__ndim > 1) { HYPRE_XCONCAT3(hypre__stride,1,k) = stridek[1]; } \ if (hypre__ndim > 2) { HYPRE_XCONCAT3(hypre__stride,2,k) = stridek[2]; } \ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * v2 * device code for BoxLoop 1, set i1 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopSet1Body_v2(j, i1) \ i1 += ( hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j) ) * HYPRE_XCONCAT3(hypre__stride,j,1);\ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); #define zypre_omp4_BoxLoopSet1_v2(i1, idx) \ HYPRE_Int hypre__J, i1, idx; \ idx = hypre__J = hypre__thread; i1 = 0; \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet1Body_v2(0, i1) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet1Body_v2(1, i1) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet1Body_v2(2, i1) } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * v2: Basic * BoxLoop 1 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop1_v2_Begin(ndim, loop_size, stride1, i1, idx) \ {\ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit_v2(1, stride1) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE1 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ {\ zypre_omp4_BoxLoopSet1_v2(i1, idx) /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * v2 * device code for BoxLoop 2, set i1, i2 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_BoxLoopSet2Body_v2(j, i1, i2) \ hypre__i = hypre__J % HYPRE_XCONCAT2(hypre__loop_size,j); \ /* twice */ \ i1 += hypre__i * HYPRE_XCONCAT3(hypre__stride,j,1); \ i2 += hypre__i * HYPRE_XCONCAT3(hypre__stride,j,2); \ hypre__J /= HYPRE_XCONCAT2(hypre__loop_size,j); #define zypre_omp4_BoxLoopSet2_v2(i1, i2) \ HYPRE_Int hypre__i, hypre__J, i1, i2; \ hypre__J = hypre__thread; i1 = i2 = 0; \ /*if (hypre__ndim > 0)*/ { zypre_omp4_BoxLoopSet2Body_v2(0, i1, i2) } \ if (hypre__ndim > 1) { zypre_omp4_BoxLoopSet2Body_v2(1, i1, i2) } \ if (hypre__ndim > 2) { zypre_omp4_BoxLoopSet2Body_v2(2, i1, i2) } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * v2: Basic * BoxLoop 2 * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_omp4_dist_BoxLoop2_v2_Begin(ndim, loop_size, stride1, i1, stride2, i2) \ { \ /* host code: */ \ HYPRE_BOXLOOP_ENTRY_PRINT \ zypre_omp4_BoxLoopDeclareInit(ndim, loop_size) \ zypre_omp4_BoxKDeclareInit_v2(1, stride1) \ zypre_omp4_BoxKDeclareInit_v2(2, stride2) \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE2 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int hypre__thread = 0; hypre__thread < hypre__tot; hypre__thread++) \ { \ zypre_omp4_BoxLoopSet2_v2(i1, i2) /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - * Basic Loop * - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #define zypre_LoopBegin(size, idx) \ { \ /* host code: */ \ /* HYPRE_Int idx = 0; */\ HYPRE_Int hypre__tot = size; \ HYPRE_BOXLOOP_ENTRY_PRINT \ /* device code: */ \ _Pragma (HYPRE_XSTR(omp target teams distribute parallel for IF_CLAUSE MAP_CLAUSE2 IS_DEVICE_CLAUSE TEAM_CLAUSE)) \ for (HYPRE_Int idx = 0; idx < hypre__tot; idx++) \ { #if 0 #define hypre_LoopBegin0(size, idx) \ { \ HYPRE_Int idx, hypre__size = size; \ for (idx = 0; idx < hypre__size; idx++) \ { #define hypre_newBoxLoopGetIndex(index) \ index[0] = hypre__id_0; \ index[1] = hypre__id_1; \ index[2] = hypre__id_2; #endif /* Reduction */ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, reducesum) \ hypre_BoxLoop1Begin(ndim, loop_size, dbox1, start1, stride1, i1) #define hypre_BoxLoop1ReductionEnd(i1, reducesum) \ hypre_BoxLoop1End(i1) #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, reducesum) \ hypre_BoxLoop2Begin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) #define hypre_BoxLoop2ReductionEnd(i1, i2, reducesum) \ hypre_BoxLoop2End(i1, i2) #endif #else /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_NEWBOXLOOP_HEADER #define HYPRE_NEWBOXLOOP_HEADER #ifdef HYPRE_USING_OPENMP #define HYPRE_BOX_REDUCTION #ifdef WIN32 #define Pragma(x) __pragma(HYPRE_XSTR(x)) #else #define Pragma(x) _Pragma(HYPRE_XSTR(x)) #endif #define OMP1 Pragma(omp parallel for private(HYPRE_BOX_PRIVATE) HYPRE_BOX_REDUCTION HYPRE_SMP_SCHEDULE) #else #define OMP1 #endif typedef struct hypre_Boxloop_struct { HYPRE_Int lsize0,lsize1,lsize2; HYPRE_Int strides0,strides1,strides2; HYPRE_Int bstart0,bstart1,bstart2; HYPRE_Int bsize0,bsize1,bsize2; } hypre_Boxloop; #define zypre_newBoxLoop0Begin(ndim, loop_size) \ { \ zypre_BoxLoopDeclare(); \ zypre_BoxLoopInit(ndim, loop_size); \ OMP1 \ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) \ { \ zypre_BoxLoopSet(); \ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++) \ { \ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++) \ { #define zypre_newBoxLoop0End() \ } \ zypre_BoxLoopInc1(); \ zypre_BoxLoopInc2(); \ } \ } \ } #define zypre_newBoxLoop1Begin(ndim, loop_size, \ dbox1, start1, stride1, i1) \ { \ HYPRE_Int i1; \ zypre_BoxLoopDeclare(); \ zypre_BoxLoopDeclareK(1); \ zypre_BoxLoopInit(ndim, loop_size); \ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1); \ OMP1 \ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) \ { \ HYPRE_Int i1; \ zypre_BoxLoopSet(); \ zypre_BoxLoopSetK(1, i1); \ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++) \ { \ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++) \ { #define zypre_newBoxLoop1End(i1) \ i1 += hypre__i0inc1; \ } \ zypre_BoxLoopInc1(); \ i1 += hypre__ikinc1[hypre__d]; \ zypre_BoxLoopInc2(); \ } \ } \ } #define zypre_newBoxLoop2Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) \ { \ HYPRE_Int i1, i2; \ zypre_BoxLoopDeclare(); \ zypre_BoxLoopDeclareK(1); \ zypre_BoxLoopDeclareK(2); \ zypre_BoxLoopInit(ndim, loop_size); \ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1); \ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2); \ OMP1 \ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) \ { \ HYPRE_Int i1, i2; \ zypre_BoxLoopSet(); \ zypre_BoxLoopSetK(1, i1); \ zypre_BoxLoopSetK(2, i2); \ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++) \ { \ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++) \ { #define zypre_newBoxLoop2End(i1, i2) \ i1 += hypre__i0inc1; \ i2 += hypre__i0inc2; \ } \ zypre_BoxLoopInc1(); \ i1 += hypre__ikinc1[hypre__d]; \ i2 += hypre__ikinc2[hypre__d]; \ zypre_BoxLoopInc2(); \ } \ } \ } #define zypre_newBoxLoop3Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ { \ HYPRE_Int i1, i2, i3; \ zypre_BoxLoopDeclare(); \ zypre_BoxLoopDeclareK(1); \ zypre_BoxLoopDeclareK(2); \ zypre_BoxLoopDeclareK(3); \ zypre_BoxLoopInit(ndim, loop_size); \ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1); \ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2); \ zypre_BoxLoopInitK(3, dbox3, start3, stride3, i3); \ OMP1 \ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) \ { \ HYPRE_Int i1, i2, i3; \ zypre_BoxLoopSet(); \ zypre_BoxLoopSetK(1, i1); \ zypre_BoxLoopSetK(2, i2); \ zypre_BoxLoopSetK(3, i3); \ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++) \ { \ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++) \ { #define zypre_newBoxLoop3End(i1, i2, i3) \ i1 += hypre__i0inc1; \ i2 += hypre__i0inc2; \ i3 += hypre__i0inc3; \ } \ zypre_BoxLoopInc1(); \ i1 += hypre__ikinc1[hypre__d]; \ i2 += hypre__ikinc2[hypre__d]; \ i3 += hypre__ikinc3[hypre__d]; \ zypre_BoxLoopInc2(); \ } \ } \ } #define zypre_newBoxLoop4Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ { \ HYPRE_Int i1, i2, i3, i4; \ zypre_BoxLoopDeclare(); \ zypre_BoxLoopDeclareK(1); \ zypre_BoxLoopDeclareK(2); \ zypre_BoxLoopDeclareK(3); \ zypre_BoxLoopDeclareK(4); \ zypre_BoxLoopInit(ndim, loop_size); \ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1); \ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2); \ zypre_BoxLoopInitK(3, dbox3, start3, stride3, i3); \ zypre_BoxLoopInitK(4, dbox4, start4, stride4, i4); \ OMP1 \ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) \ { \ HYPRE_Int i1, i2, i3, i4; \ zypre_BoxLoopSet(); \ zypre_BoxLoopSetK(1, i1); \ zypre_BoxLoopSetK(2, i2); \ zypre_BoxLoopSetK(3, i3); \ zypre_BoxLoopSetK(4, i4); \ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++) \ { \ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++) \ { #define zypre_newBoxLoop4End(i1, i2, i3, i4) \ i1 += hypre__i0inc1; \ i2 += hypre__i0inc2; \ i3 += hypre__i0inc3; \ i4 += hypre__i0inc4; \ } \ zypre_BoxLoopInc1(); \ i1 += hypre__ikinc1[hypre__d]; \ i2 += hypre__ikinc2[hypre__d]; \ i3 += hypre__ikinc3[hypre__d]; \ i4 += hypre__ikinc4[hypre__d]; \ zypre_BoxLoopInc2(); \ } \ } \ } #define zypre_newBasicBoxLoop2Begin(ndim, loop_size, \ stride1, i1, \ stride2, i2) \ { \ zypre_BoxLoopDeclare(); \ zypre_BoxLoopDeclareK(1); \ zypre_BoxLoopDeclareK(2); \ zypre_BoxLoopInit(ndim, loop_size); \ zypre_BasicBoxLoopInitK(1, stride1); \ zypre_BasicBoxLoopInitK(2, stride2); \ OMP1 \ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) \ { \ HYPRE_Int i1, i2; \ zypre_BoxLoopSet(); \ zypre_BoxLoopSetK(1, i1); \ zypre_BoxLoopSetK(2, i2); \ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++) \ { \ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++) \ { #define hypre_LoopBegin(size,idx) \ { \ HYPRE_Int idx; \ for (idx = 0;idx < size;idx ++) \ { #define hypre_LoopEnd() \ } \ } #define hypre_newBoxLoopGetIndex zypre_BoxLoopGetIndex #define hypre_BoxLoopGetIndex zypre_BoxLoopGetIndex #define hypre_BoxLoopSetOneBlock zypre_BoxLoopSetOneBlock #define hypre_BoxLoopBlock zypre_BoxLoopBlock #define hypre_BoxLoop0Begin zypre_newBoxLoop0Begin #define hypre_BoxLoop0End zypre_newBoxLoop0End #define hypre_BoxLoop1Begin zypre_newBoxLoop1Begin #define hypre_BoxLoop1End zypre_newBoxLoop1End #define hypre_BoxLoop2Begin zypre_newBoxLoop2Begin #define hypre_BoxLoop2End zypre_newBoxLoop2End #define hypre_BoxLoop3Begin zypre_newBoxLoop3Begin #define hypre_BoxLoop3End zypre_newBoxLoop3End #define hypre_BoxLoop4Begin zypre_newBoxLoop4Begin #define hypre_BoxLoop4End zypre_newBoxLoop4End #define hypre_BasicBoxLoop2Begin zypre_newBasicBoxLoop2Begin /* Reduction */ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, reducesum) \ hypre_BoxLoop1Begin(ndim, loop_size, dbox1, start1, stride1, i1) #define hypre_BoxLoop1ReductionEnd(i1, reducesum) \ hypre_BoxLoop1End(i1) #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, reducesum) \ hypre_BoxLoop2Begin(ndim, loop_size, dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) #define hypre_BoxLoop2ReductionEnd(i1, i2, reducesum) \ hypre_BoxLoop2End(i1, i2) #endif #endif #ifdef __cplusplus extern "C" { #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the Box structures * *****************************************************************************/ #ifndef hypre_BOX_HEADER #define hypre_BOX_HEADER #ifndef HYPRE_MAXDIM #define HYPRE_MAXDIM 3 #endif /*-------------------------------------------------------------------------- * hypre_Index: * This is used to define indices in index space, or dimension * sizes of boxes. * * The spatial dimensions x, y, and z may be specified by the * integers 0, 1, and 2, respectively (see the hypre_IndexD macro below). * This simplifies the code in the hypre_Box class by reducing code * replication. *--------------------------------------------------------------------------*/ typedef HYPRE_Int hypre_Index[HYPRE_MAXDIM]; typedef HYPRE_Int *hypre_IndexRef; /*-------------------------------------------------------------------------- * hypre_Box: *--------------------------------------------------------------------------*/ typedef struct hypre_Box_struct { hypre_Index imin; /* min bounding indices */ hypre_Index imax; /* max bounding indices */ HYPRE_Int ndim; /* number of dimensions */ } hypre_Box; /*-------------------------------------------------------------------------- * hypre_BoxArray: * An array of boxes. * Since size can be zero, need to store ndim separately. *--------------------------------------------------------------------------*/ typedef struct hypre_BoxArray_struct { hypre_Box *boxes; /* Array of boxes */ HYPRE_Int size; /* Size of box array */ HYPRE_Int alloc_size; /* Size of currently alloced space */ HYPRE_Int ndim; /* number of dimensions */ } hypre_BoxArray; #define hypre_BoxArrayExcess 10 /*-------------------------------------------------------------------------- * hypre_BoxArrayArray: * An array of box arrays. * Since size can be zero, need to store ndim separately. *--------------------------------------------------------------------------*/ typedef struct hypre_BoxArrayArray_struct { hypre_BoxArray **box_arrays; /* Array of pointers to box arrays */ HYPRE_Int size; /* Size of box array array */ HYPRE_Int ndim; /* number of dimensions */ } hypre_BoxArrayArray; /*-------------------------------------------------------------------------- * Accessor macros: hypre_Index *--------------------------------------------------------------------------*/ #define hypre_IndexD(index, d) (index[d]) /* Avoid using these macros */ #define hypre_IndexX(index) hypre_IndexD(index, 0) #define hypre_IndexY(index) hypre_IndexD(index, 1) #define hypre_IndexZ(index) hypre_IndexD(index, 2) /*-------------------------------------------------------------------------- * Member functions: hypre_Index *--------------------------------------------------------------------------*/ /*----- Avoid using these Index macros -----*/ #define hypre_SetIndex3(index, ix, iy, iz) \ ( hypre_IndexD(index, 0) = ix,\ hypre_IndexD(index, 1) = iy,\ hypre_IndexD(index, 2) = iz ) #define hypre_ClearIndex(index) hypre_SetIndex(index, 0) /*-------------------------------------------------------------------------- * Accessor macros: hypre_Box *--------------------------------------------------------------------------*/ #define hypre_BoxIMin(box) ((box) -> imin) #define hypre_BoxIMax(box) ((box) -> imax) #define hypre_BoxNDim(box) ((box) -> ndim) #define hypre_BoxIMinD(box, d) (hypre_IndexD(hypre_BoxIMin(box), d)) #define hypre_BoxIMaxD(box, d) (hypre_IndexD(hypre_BoxIMax(box), d)) #define hypre_BoxSizeD(box, d) \ hypre_max(0, (hypre_BoxIMaxD(box, d) - hypre_BoxIMinD(box, d) + 1)) #define hypre_IndexDInBox(index, d, box) \ ( hypre_IndexD(index, d) >= hypre_BoxIMinD(box, d) && \ hypre_IndexD(index, d) <= hypre_BoxIMaxD(box, d) ) /* The first hypre_CCBoxIndexRank is better style because it is similar to hypre_BoxIndexRank. The second one sometimes avoids compiler warnings. */ #define hypre_CCBoxIndexRank(box, index) 0 #define hypre_CCBoxIndexRank_noargs() 0 #define hypre_CCBoxOffsetDistance(box, index) 0 /*----- Avoid using these Box macros -----*/ #define hypre_BoxSizeX(box) hypre_BoxSizeD(box, 0) #define hypre_BoxSizeY(box) hypre_BoxSizeD(box, 1) #define hypre_BoxSizeZ(box) hypre_BoxSizeD(box, 2) /*-------------------------------------------------------------------------- * Accessor macros: hypre_BoxArray *--------------------------------------------------------------------------*/ #define hypre_BoxArrayBoxes(box_array) ((box_array) -> boxes) #define hypre_BoxArrayBox(box_array, i) &((box_array) -> boxes[(i)]) #define hypre_BoxArraySize(box_array) ((box_array) -> size) #define hypre_BoxArrayAllocSize(box_array) ((box_array) -> alloc_size) #define hypre_BoxArrayNDim(box_array) ((box_array) -> ndim) /*-------------------------------------------------------------------------- * Accessor macros: hypre_BoxArrayArray *--------------------------------------------------------------------------*/ #define hypre_BoxArrayArrayBoxArrays(box_array_array) \ ((box_array_array) -> box_arrays) #define hypre_BoxArrayArrayBoxArray(box_array_array, i) \ ((box_array_array) -> box_arrays[(i)]) #define hypre_BoxArrayArraySize(box_array_array) \ ((box_array_array) -> size) #define hypre_BoxArrayArrayNDim(box_array_array) \ ((box_array_array) -> ndim) /*-------------------------------------------------------------------------- * Looping macros: *--------------------------------------------------------------------------*/ #define hypre_ForBoxI(i, box_array) \ for (i = 0; i < hypre_BoxArraySize(box_array); i++) #define hypre_ForBoxArrayI(i, box_array_array) \ for (i = 0; i < hypre_BoxArrayArraySize(box_array_array); i++) /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #define hypre_SerialBoxLoop0Begin(ndim, loop_size)\ {\ zypre_BoxLoopDeclare();\ zypre_BoxLoopInit(ndim, loop_size);\ hypre_BoxLoopSetOneBlock();\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ zypre_BoxLoopSet();\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define hypre_SerialBoxLoop0End()\ }\ zypre_BoxLoopInc1();\ zypre_BoxLoopInc2();\ }\ }\ } #define hypre_SerialBoxLoop1Begin(ndim, loop_size,\ dbox1, start1, stride1, i1)\ {\ HYPRE_Int i1;\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1);\ zypre_BoxLoopSetOneBlock();\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ zypre_BoxLoopSet();\ zypre_BoxLoopSetK(1, i1);\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define hypre_SerialBoxLoop1End(i1)\ i1 += hypre__i0inc1;\ }\ zypre_BoxLoopInc1();\ i1 += hypre__ikinc1[hypre__d];\ zypre_BoxLoopInc2();\ }\ }\ } #define hypre_SerialBoxLoop2Begin(ndim, loop_size,\ dbox1, start1, stride1, i1,\ dbox2, start2, stride2, i2)\ {\ HYPRE_Int i1,i2;\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopDeclareK(2);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1);\ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2);\ zypre_BoxLoopSetOneBlock();\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ zypre_BoxLoopSet();\ zypre_BoxLoopSetK(1, i1);\ zypre_BoxLoopSetK(2, i2);\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define hypre_SerialBoxLoop2End(i1, i2)\ i1 += hypre__i0inc1;\ i2 += hypre__i0inc2;\ }\ zypre_BoxLoopInc1();\ i1 += hypre__ikinc1[hypre__d];\ i2 += hypre__ikinc2[hypre__d];\ zypre_BoxLoopInc2();\ }\ }\ } #define ZYPRE_BOX_PRIVATE hypre__IN,hypre__JN,hypre__I,hypre__J,hypre__d,hypre__i #define HYPRE_BOX_PRIVATE ZYPRE_BOX_PRIVATE #define zypre_BoxLoopDeclare() \ HYPRE_Int hypre__tot, hypre__div, hypre__mod;\ HYPRE_Int hypre__block, hypre__num_blocks;\ HYPRE_Int hypre__d, hypre__ndim;\ HYPRE_Int hypre__I, hypre__J, hypre__IN, hypre__JN;\ HYPRE_Int hypre__i[HYPRE_MAXDIM+1], hypre__n[HYPRE_MAXDIM+1] #define zypre_BoxLoopDeclareK(k) \ HYPRE_Int hypre__ikstart##k, hypre__i0inc##k;\ HYPRE_Int hypre__sk##k[HYPRE_MAXDIM], hypre__ikinc##k[HYPRE_MAXDIM+1] #define zypre_BoxLoopInit(ndim, loop_size) \ hypre__ndim = ndim;\ hypre__n[0] = loop_size[0];\ hypre__tot = 1;\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ hypre__n[hypre__d] = loop_size[hypre__d];\ hypre__tot *= hypre__n[hypre__d];\ }\ hypre__n[hypre__ndim] = 2;\ hypre__num_blocks = hypre_NumThreads();\ if (hypre__tot < hypre__num_blocks)\ {\ hypre__num_blocks = hypre__tot;\ }\ if (hypre__num_blocks > 0)\ {\ hypre__div = hypre__tot / hypre__num_blocks;\ hypre__mod = hypre__tot % hypre__num_blocks;\ } #define zypre_BoxLoopInitK(k, dboxk, startk, stridek, ik) \ hypre__sk##k[0] = stridek[0];\ hypre__ikinc##k[0] = 0;\ ik = hypre_BoxSizeD(dboxk, 0); /* temporarily use ik */\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ hypre__sk##k[hypre__d] = ik*stridek[hypre__d];\ hypre__ikinc##k[hypre__d] = hypre__ikinc##k[hypre__d-1] +\ hypre__sk##k[hypre__d] - hypre__n[hypre__d-1]*hypre__sk##k[hypre__d-1];\ ik *= hypre_BoxSizeD(dboxk, hypre__d);\ }\ hypre__i0inc##k = hypre__sk##k[0];\ hypre__ikinc##k[hypre__ndim] = 0;\ hypre__ikstart##k = hypre_BoxIndexRank(dboxk, startk) #define zypre_BoxLoopSet() \ hypre__IN = hypre__n[0];\ if (hypre__num_blocks > 1)/* in case user sets num_blocks to 1 */\ {\ hypre__JN = hypre__div + ((hypre__mod > hypre__block) ? 1 : 0);\ hypre__J = hypre__block * hypre__div + hypre_min(hypre__mod, hypre__block);\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ hypre__i[hypre__d] = hypre__J % hypre__n[hypre__d];\ hypre__J /= hypre__n[hypre__d];\ }\ }\ else\ {\ hypre__JN = hypre__tot;\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ hypre__i[hypre__d] = 0;\ }\ }\ hypre__i[hypre__ndim] = 0 #define zypre_BoxLoopSetK(k, ik) \ ik = hypre__ikstart##k;\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ ik += hypre__i[hypre__d]*hypre__sk##k[hypre__d];\ } #define zypre_BoxLoopInc1() \ hypre__d = 1;\ while ((hypre__i[hypre__d]+2) > hypre__n[hypre__d])\ {\ hypre__d++;\ } #define zypre_BoxLoopInc2() \ hypre__i[hypre__d]++;\ while (hypre__d > 1)\ {\ hypre__d--;\ hypre__i[hypre__d] = 0;\ } /* This returns the loop index (of type hypre_Index) for the current iteration, * where the numbering starts at 0. It works even when threading is turned on, * as long as 'index' is declared to be private. */ #define zypre_BoxLoopGetIndex(index) \ index[0] = hypre__I;\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ index[hypre__d] = hypre__i[hypre__d];\ } /* Use this before the For macros below to force only one block */ #define zypre_BoxLoopSetOneBlock() hypre__num_blocks = 1 /* Use this to get the block iteration inside a BoxLoop */ #define zypre_BoxLoopBlock() hypre__block /* FIXME: Remove !!! */ /*-----------------------------------*/ #define zypre_BoxLoop0Begin(ndim, loop_size)\ {\ zypre_BoxLoopDeclare();\ zypre_BoxLoopInit(ndim, loop_size); #define zypre_BoxLoop0For()\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ zypre_BoxLoopSet();\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define zypre_BoxLoop0End()\ }\ zypre_BoxLoopInc1();\ zypre_BoxLoopInc2();\ }\ }\ } /*-----------------------------------*/ #define zypre_BoxLoop1Begin(ndim, loop_size,\ dbox1, start1, stride1, i1)\ {\ HYPRE_Int i1;\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1); #define zypre_BoxLoop1For(i1)\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ HYPRE_Int i1;\ zypre_BoxLoopSet();\ zypre_BoxLoopSetK(1, i1);\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define zypre_BoxLoop1End(i1)\ i1 += hypre__i0inc1;\ }\ zypre_BoxLoopInc1();\ i1 += hypre__ikinc1[hypre__d];\ zypre_BoxLoopInc2();\ }\ }\ } /*-----------------------------------*/ #define zypre_BoxLoop2Begin(ndim, loop_size,\ dbox1, start1, stride1, i1,\ dbox2, start2, stride2, i2)\ {\ HYPRE_Int i1,i2;\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopDeclareK(2);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1);\ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2); #define zypre_BoxLoop2For(i1, i2)\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ HYPRE_Int i1,i2;\ zypre_BoxLoopSet();\ zypre_BoxLoopSetK(1, i1);\ zypre_BoxLoopSetK(2, i2);\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define zypre_BoxLoop2End(i1, i2)\ i1 += hypre__i0inc1;\ i2 += hypre__i0inc2;\ }\ zypre_BoxLoopInc1();\ i1 += hypre__ikinc1[hypre__d];\ i2 += hypre__ikinc2[hypre__d];\ zypre_BoxLoopInc2();\ }\ }\ } /*-----------------------------------*/ #define zypre_BoxLoop3Begin(ndim, loop_size,\ dbox1, start1, stride1, i1,\ dbox2, start2, stride2, i2,\ dbox3, start3, stride3, i3)\ {\ HYPRE_Int i1,i2,i3;\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopDeclareK(2);\ zypre_BoxLoopDeclareK(3);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1);\ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2);\ zypre_BoxLoopInitK(3, dbox3, start3, stride3, i3); #define zypre_BoxLoop3For(i1, i2, i3)\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ HYPRE_Int i1,i2,i3;\ zypre_BoxLoopSet();\ zypre_BoxLoopSetK(1, i1);\ zypre_BoxLoopSetK(2, i2);\ zypre_BoxLoopSetK(3, i3);\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define zypre_BoxLoop3End(i1, i2, i3)\ i1 += hypre__i0inc1;\ i2 += hypre__i0inc2;\ i3 += hypre__i0inc3;\ }\ zypre_BoxLoopInc1();\ i1 += hypre__ikinc1[hypre__d];\ i2 += hypre__ikinc2[hypre__d];\ i3 += hypre__ikinc3[hypre__d];\ zypre_BoxLoopInc2();\ }\ }\ } /*-----------------------------------*/ #define zypre_BoxLoop4Begin(ndim, loop_size,\ dbox1, start1, stride1, i1,\ dbox2, start2, stride2, i2,\ dbox3, start3, stride3, i3,\ dbox4, start4, stride4, i4)\ {\ HYPRE_Int i1,i2,i3,i4;\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopDeclareK(2);\ zypre_BoxLoopDeclareK(3);\ zypre_BoxLoopDeclareK(4);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BoxLoopInitK(1, dbox1, start1, stride1, i1);\ zypre_BoxLoopInitK(2, dbox2, start2, stride2, i2);\ zypre_BoxLoopInitK(3, dbox3, start3, stride3, i3);\ zypre_BoxLoopInitK(4, dbox4, start4, stride4, i4); #define zypre_BoxLoop4For(i1, i2, i3, i4)\ for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++)\ {\ HYPRE_Int i1,i2,i3,i4;\ zypre_BoxLoopSet();\ zypre_BoxLoopSetK(1, i1);\ zypre_BoxLoopSetK(2, i2);\ zypre_BoxLoopSetK(3, i3);\ zypre_BoxLoopSetK(4, i4);\ for (hypre__J = 0; hypre__J < hypre__JN; hypre__J++)\ {\ for (hypre__I = 0; hypre__I < hypre__IN; hypre__I++)\ { #define zypre_BoxLoop4End(i1, i2, i3, i4)\ i1 += hypre__i0inc1;\ i2 += hypre__i0inc2;\ i3 += hypre__i0inc3;\ i4 += hypre__i0inc4;\ }\ zypre_BoxLoopInc1();\ i1 += hypre__ikinc1[hypre__d];\ i2 += hypre__ikinc2[hypre__d];\ i3 += hypre__ikinc3[hypre__d];\ i4 += hypre__ikinc4[hypre__d];\ zypre_BoxLoopInc2();\ }\ }\ } /*-----------------------------------*/ #define zypre_BasicBoxLoopInitK(k, stridek) \ hypre__sk##k[0] = stridek[0];\ hypre__ikinc##k[0] = 0;\ for (hypre__d = 1; hypre__d < hypre__ndim; hypre__d++)\ {\ hypre__sk##k[hypre__d] = stridek[hypre__d];\ hypre__ikinc##k[hypre__d] = hypre__ikinc##k[hypre__d-1] +\ hypre__sk##k[hypre__d] - hypre__n[hypre__d-1]*hypre__sk##k[hypre__d-1];\ }\ hypre__i0inc##k = hypre__sk##k[0];\ hypre__ikinc##k[hypre__ndim] = 0;\ hypre__ikstart##k = 0 #define zypre_BasicBoxLoop2Begin(ndim, loop_size,\ stride1, i1,\ stride2, i2)\ {\ zypre_BoxLoopDeclare();\ zypre_BoxLoopDeclareK(1);\ zypre_BoxLoopDeclareK(2);\ zypre_BoxLoopInit(ndim, loop_size);\ zypre_BasicBoxLoopInitK(1, stride1);\ zypre_BasicBoxLoopInitK(2, stride2); /*-----------------------------------*/ #endif /*-------------------------------------------------------------------------- * NOTES - Keep these for reference here and elsewhere in the code *--------------------------------------------------------------------------*/ #if 0 #define hypre_BoxLoop2Begin(loop_size, dbox1, start1, stride1, i1, dbox2, start2, stride2, i2) { /* init hypre__i1start */ HYPRE_Int hypre__i1start = hypre_BoxIndexRank(dbox1, start1); HYPRE_Int hypre__i2start = hypre_BoxIndexRank(dbox2, start2); /* declare and set hypre__s1 */ hypre_BoxLoopDeclareS(dbox1, stride1, hypre__sx1, hypre__sy1, hypre__sz1); hypre_BoxLoopDeclareS(dbox2, stride2, hypre__sx2, hypre__sy2, hypre__sz2); /* declare and set hypre__n, hypre__m, hypre__dir, hypre__max, * hypre__div, hypre__mod, hypre__block, hypre__num_blocks */ hypre_BoxLoopDeclareN(loop_size); #define hypre_BoxLoop2For(i, j, k, i1, i2) for (hypre__block = 0; hypre__block < hypre__num_blocks; hypre__block++) { /* set i and hypre__n */ hypre_BoxLoopSet(i, j, k); /* set i1 */ i1 = hypre__i1start + i*hypre__sx1 + j*hypre__sy1 + k*hypre__sz1; i2 = hypre__i2start + i*hypre__sx2 + j*hypre__sy2 + k*hypre__sz2; for (k = 0; k < hypre__nz; k++) { for (j = 0; j < hypre__ny; j++) { for (i = 0; i < hypre__nx; i++) { #define hypre_BoxLoop2End(i1, i2) i1 += hypre__sx1; i2 += hypre__sx2; } i1 += hypre__sy1 - hypre__nx*hypre__sx1; i2 += hypre__sy2 - hypre__nx*hypre__sx2; } i1 += hypre__sz1 - hypre__ny*hypre__sy1; i2 += hypre__sz2 - hypre__ny*hypre__sy2; } } } /*---------------------------------------- * Idea 2: Simple version of Idea 3 below *----------------------------------------*/ N = 1; for (d = 0; d < ndim; d++) { N *= n[d]; i[d] = 0; n[d] -= 2; /* this produces a simpler comparison below */ } i[ndim] = 0; n[ndim] = 0; for (I = 0; I < N; I++) { /* loop body */ for (d = 0; i[d] > n[d]; d++) { i[d] = 0; } i[d]++; i1 += s1[d]; /* NOTE: These are different from hypre__sx1, etc. above */ i2 += s2[d]; /* The lengths of i, n, and s must be (ndim+1) */ } /*---------------------------------------- * Idea 3: Approach used in the box loops *----------------------------------------*/ N = 1; for (d = 1; d < ndim; d++) { N *= n[d]; i[d] = 0; n[d] -= 2; /* this produces a simpler comparison below */ } i[ndim] = 0; n[ndim] = 0; for (J = 0; J < N; J++) { for (I = 0; I < n[0]; I++) { /* loop body */ i1 += s1[0]; i2 += s2[0]; } for (d = 1; i[d] > n[d]; d++) { i[d] = 0; } i[d]++; i1 += s1[d]; /* NOTE: These are different from hypre__sx1, etc. above */ i2 += s2[d]; /* The lengths of i, n, and s must be (ndim+1) */ } #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the struct assumed partition * *****************************************************************************/ #ifndef hypre_ASSUMED_PART_HEADER #define hypre_ASSUMED_PART_HEADER typedef struct { /* the entries will be the same for all procs */ HYPRE_Int ndim; /* number of dimensions */ hypre_BoxArray *regions; /* areas of the grid with boxes */ HYPRE_Int num_regions; /* how many regions */ HYPRE_Int *proc_partitions; /* proc ids assigned to each region (this is size num_regions +1) */ hypre_Index *divisions; /* number of proc divisions in each direction for each region */ /* these entries are specific to each proc */ hypre_BoxArray *my_partition; /* my portion of grid (at most 2) */ hypre_BoxArray *my_partition_boxes; /* boxes in my portion */ HYPRE_Int *my_partition_proc_ids; HYPRE_Int *my_partition_boxnums; HYPRE_Int my_partition_ids_size; HYPRE_Int my_partition_ids_alloc; HYPRE_Int my_partition_num_distinct_procs; } hypre_StructAssumedPart; /*Accessor macros */ #define hypre_StructAssumedPartNDim(apart) ((apart)->ndim) #define hypre_StructAssumedPartRegions(apart) ((apart)->regions) #define hypre_StructAssumedPartNumRegions(apart) ((apart)->num_regions) #define hypre_StructAssumedPartDivisions(apart) ((apart)->divisions) #define hypre_StructAssumedPartDivision(apart, i) ((apart)->divisions[i]) #define hypre_StructAssumedPartProcPartitions(apart) ((apart)->proc_partitions) #define hypre_StructAssumedPartProcPartition(apart, i) ((apart)->proc_partitions[i]) #define hypre_StructAssumedPartMyPartition(apart) ((apart)->my_partition) #define hypre_StructAssumedPartMyPartitionBoxes(apart) ((apart)->my_partition_boxes) #define hypre_StructAssumedPartMyPartitionProcIds(apart) ((apart)->my_partition_proc_ids) #define hypre_StructAssumedPartMyPartitionIdsSize(apart) ((apart)->my_partition_ids_size) #define hypre_StructAssumedPartMyPartitionIdsAlloc(apart) ((apart)->my_partition_ids_alloc) #define hypre_StructAssumedPartMyPartitionNumDistinctProcs(apart) ((apart)->my_partition_num_distinct_procs) #define hypre_StructAssumedPartMyPartitionBoxnums(apart) ((apart)->my_partition_boxnums) #define hypre_StructAssumedPartMyPartitionProcId(apart, i) ((apart)->my_partition_proc_ids[i]) #define hypre_StructAssumedPartMyPartitionBoxnum(apart, i) ((apart)->my_partition_boxnums[i]) #endif /****************************************************************************** * 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) ******************************************************************************/ #ifndef hypre_BOX_MANAGER_HEADER #define hypre_BOX_MANAGER_HEADER /*-------------------------------------------------------------------------- * BoxManEntry *--------------------------------------------------------------------------*/ typedef struct hypre_BoxManEntry_struct { hypre_Index imin; /* Extents of box */ hypre_Index imax; HYPRE_Int ndim; /* Number of dimensions */ HYPRE_Int proc; /* This is a two-part unique id: (proc, id) */ HYPRE_Int id; HYPRE_Int num_ghost[2*HYPRE_MAXDIM]; HYPRE_Int position; /* This indicates the location of the entry in the the * box manager entries array and is used for pairing with * the info object (populated in addentry) */ void *boxman; /* The owning manager (populated in addentry) */ struct hypre_BoxManEntry_struct *next; } hypre_BoxManEntry; /*--------------------------------------------------------------------------- * Box Manager: organizes arbitrary information in a spatial way *----------------------------------------------------------------------------*/ typedef struct { MPI_Comm comm; HYPRE_Int max_nentries; /* storage allocated for entries */ HYPRE_Int is_gather_called; /* Boolean to indicate whether GatherEntries function has been called (prior to assemble) - may not want this (can tell by the size of gather_regions array) */ hypre_BoxArray *gather_regions; /* This is where we collect boxes input by calls to BoxManGatherEntries - to be gathered in the assemble. These are then deleted after the assemble */ HYPRE_Int all_global_known; /* Boolean to say that every processor already has all of the global data for this manager (this could be accessed by a coarsening routine, for example) */ HYPRE_Int is_entries_sort; /* Boolean to say that entries were added in sorted order (id, proc) (this could be accessed by a coarsening routine, for example) */ HYPRE_Int entry_info_size; /* In bytes, the (max) size of the info object for the entries */ HYPRE_Int is_assembled; /* Flag to indicate if the box manager has been assembled (used to control whether or not functions can be used prior to assemble) */ /* Storing the entries */ HYPRE_Int nentries; /* Number of entries stored */ hypre_BoxManEntry *entries; /* Actual box manager entries - sorted by (proc, id) at the end of the assemble) */ HYPRE_Int *procs_sort; /* The sorted procs corresponding to entries */ HYPRE_Int *ids_sort; /* Sorted ids corresponding to the entries */ HYPRE_Int num_procs_sort; /* Number of distinct procs in entries */ HYPRE_Int *procs_sort_offsets; /* Offsets for procs into the entry_sort array */ HYPRE_Int first_local; /* Position of local infomation in entries */ HYPRE_Int local_proc_offset; /* Position of local information in offsets */ /* Here is the table that organizes the entries spatially (by index) */ hypre_BoxManEntry **index_table; /* This points into 'entries' array and corresponds to the index arays */ HYPRE_Int *indexes[HYPRE_MAXDIM]; /* Indexes (ordered) for imin and imax of each box in the entries array */ HYPRE_Int size[HYPRE_MAXDIM]; /* How many indexes in each direction */ HYPRE_Int last_index[HYPRE_MAXDIM]; /* Last index used in the indexes map */ HYPRE_Int num_my_entries; /* Num entries with proc_id = myid */ HYPRE_Int *my_ids; /* Array of ids corresponding to my entries */ hypre_BoxManEntry **my_entries; /* Points into entries that are mine and corresponds to my_ids array. This is destroyed in the assemble. */ void *info_objects; /* Array of info objects (each of size entry_info_size), managed byte-wise */ hypre_StructAssumedPart *assumed_partition; /* The assumed partition object. For now this is only used during the assemble (where it is created). */ HYPRE_Int ndim; /* Problem dimension (known in the grid) */ hypre_Box *bounding_box; /* Bounding box from associated grid */ HYPRE_Int next_id; /* Counter to indicate the next id that would be unique (regardless of proc id) */ /* Ghost stuff */ HYPRE_Int num_ghost[2*HYPRE_MAXDIM]; } hypre_BoxManager; /*-------------------------------------------------------------------------- * Accessor macros: hypre_BoxMan *--------------------------------------------------------------------------*/ #define hypre_BoxManComm(manager) ((manager) -> comm) #define hypre_BoxManMaxNEntries(manager) ((manager) -> max_nentries) #define hypre_BoxManIsGatherCalled(manager) ((manager) -> is_gather_called) #define hypre_BoxManIsEntriesSort(manager) ((manager) -> is_entries_sort) #define hypre_BoxManGatherRegions(manager) ((manager) -> gather_regions) #define hypre_BoxManAllGlobalKnown(manager) ((manager) -> all_global_known) #define hypre_BoxManEntryInfoSize(manager) ((manager) -> entry_info_size) #define hypre_BoxManNEntries(manager) ((manager) -> nentries) #define hypre_BoxManEntries(manager) ((manager) -> entries) #define hypre_BoxManInfoObjects(manager) ((manager) -> info_objects) #define hypre_BoxManIsAssembled(manager) ((manager) -> is_assembled) #define hypre_BoxManProcsSort(manager) ((manager) -> procs_sort) #define hypre_BoxManIdsSort(manager) ((manager) -> ids_sort) #define hypre_BoxManNumProcsSort(manager) ((manager) -> num_procs_sort) #define hypre_BoxManProcsSortOffsets(manager) ((manager) -> procs_sort_offsets) #define hypre_BoxManLocalProcOffset(manager) ((manager) -> local_proc_offset) #define hypre_BoxManFirstLocal(manager) ((manager) -> first_local) #define hypre_BoxManIndexTable(manager) ((manager) -> index_table) #define hypre_BoxManIndexes(manager) ((manager) -> indexes) #define hypre_BoxManSize(manager) ((manager) -> size) #define hypre_BoxManLastIndex(manager) ((manager) -> last_index) #define hypre_BoxManNumMyEntries(manager) ((manager) -> num_my_entries) #define hypre_BoxManMyIds(manager) ((manager) -> my_ids) #define hypre_BoxManMyEntries(manager) ((manager) -> my_entries) #define hypre_BoxManAssumedPartition(manager) ((manager) -> assumed_partition) #define hypre_BoxManNDim(manager) ((manager) -> ndim) #define hypre_BoxManBoundingBox(manager) ((manager) -> bounding_box) #define hypre_BoxManNextId(manager) ((manager) -> next_id) #define hypre_BoxManNumGhost(manager) ((manager) -> num_ghost) #define hypre_BoxManIndexesD(manager, d) hypre_BoxManIndexes(manager)[d] #define hypre_BoxManSizeD(manager, d) hypre_BoxManSize(manager)[d] #define hypre_BoxManLastIndexD(manager, d) hypre_BoxManLastIndex(manager)[d] #define hypre_BoxManInfoObject(manager, i) \ (void *) ((char *)hypre_BoxManInfoObjects(manager) + i* hypre_BoxManEntryInfoSize(manager)) /*-------------------------------------------------------------------------- * Accessor macros: hypre_BoxManEntry *--------------------------------------------------------------------------*/ #define hypre_BoxManEntryIMin(entry) ((entry) -> imin) #define hypre_BoxManEntryIMax(entry) ((entry) -> imax) #define hypre_BoxManEntryNDim(entry) ((entry) -> ndim) #define hypre_BoxManEntryProc(entry) ((entry) -> proc) #define hypre_BoxManEntryId(entry) ((entry) -> id) #define hypre_BoxManEntryPosition(entry) ((entry) -> position) #define hypre_BoxManEntryNumGhost(entry) ((entry) -> num_ghost) #define hypre_BoxManEntryNext(entry) ((entry) -> next) #define hypre_BoxManEntryBoxMan(entry) ((entry) -> boxman) #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the hypre_StructGrid structures * *****************************************************************************/ #ifndef hypre_STRUCT_GRID_HEADER #define hypre_STRUCT_GRID_HEADER /*-------------------------------------------------------------------------- * hypre_StructGrid: *--------------------------------------------------------------------------*/ typedef struct hypre_StructGrid_struct { MPI_Comm comm; HYPRE_Int ndim; /* Number of grid dimensions */ hypre_BoxArray *boxes; /* Array of boxes in this process */ HYPRE_Int *ids; /* Unique IDs for boxes */ hypre_Index max_distance; /* Neighborhood size - in each dimension*/ hypre_Box *bounding_box; /* Bounding box around grid */ HYPRE_Int local_size; /* Number of grid points locally */ HYPRE_BigInt global_size; /* Total number of grid points */ hypre_Index periodic; /* Indicates if grid is periodic */ HYPRE_Int num_periods; /* number of box set periods */ hypre_Index *pshifts; /* shifts of periodicity */ HYPRE_Int ref_count; HYPRE_Int ghlocal_size; /* Number of vars in box including ghosts */ HYPRE_Int num_ghost[2*HYPRE_MAXDIM]; /* ghost layer size */ hypre_BoxManager *boxman; #if defined(HYPRE_USING_CUDA) HYPRE_Int data_location; #endif } hypre_StructGrid; /*-------------------------------------------------------------------------- * Accessor macros: hypre_StructGrid *--------------------------------------------------------------------------*/ #define hypre_StructGridComm(grid) ((grid) -> comm) #define hypre_StructGridNDim(grid) ((grid) -> ndim) #define hypre_StructGridBoxes(grid) ((grid) -> boxes) #define hypre_StructGridIDs(grid) ((grid) -> ids) #define hypre_StructGridMaxDistance(grid) ((grid) -> max_distance) #define hypre_StructGridBoundingBox(grid) ((grid) -> bounding_box) #define hypre_StructGridLocalSize(grid) ((grid) -> local_size) #define hypre_StructGridGlobalSize(grid) ((grid) -> global_size) #define hypre_StructGridPeriodic(grid) ((grid) -> periodic) #define hypre_StructGridNumPeriods(grid) ((grid) -> num_periods) #define hypre_StructGridPShifts(grid) ((grid) -> pshifts) #define hypre_StructGridPShift(grid, i) ((grid) -> pshifts[i]) #define hypre_StructGridRefCount(grid) ((grid) -> ref_count) #define hypre_StructGridGhlocalSize(grid) ((grid) -> ghlocal_size) #define hypre_StructGridNumGhost(grid) ((grid) -> num_ghost) #define hypre_StructGridBoxMan(grid) ((grid) -> boxman) #define hypre_StructGridBox(grid, i) \ (hypre_BoxArrayBox(hypre_StructGridBoxes(grid), i)) #define hypre_StructGridNumBoxes(grid) \ (hypre_BoxArraySize(hypre_StructGridBoxes(grid))) #define hypre_StructGridIDPeriod(grid) \ hypre_BoxNeighborsIDPeriod(hypre_StructGridNeighbors(grid)) #if defined(HYPRE_USING_CUDA) #define hypre_StructGridDataLocation(grid) ((grid) -> data_location) #endif /*-------------------------------------------------------------------------- * Looping macros: *--------------------------------------------------------------------------*/ #define hypre_ForStructGridBoxI(i, grid) \ hypre_ForBoxI(i, hypre_StructGridBoxes(grid)) #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for hypre_StructStencil data structures * *****************************************************************************/ #ifndef hypre_STRUCT_STENCIL_HEADER #define hypre_STRUCT_STENCIL_HEADER /*-------------------------------------------------------------------------- * hypre_StructStencil *--------------------------------------------------------------------------*/ typedef struct hypre_StructStencil_struct { hypre_Index *shape; /* Description of a stencil's shape */ HYPRE_Int size; /* Number of stencil coefficients */ HYPRE_Int ndim; /* Number of dimensions */ HYPRE_Int ref_count; } hypre_StructStencil; /*-------------------------------------------------------------------------- * Accessor functions for the hypre_StructStencil structure *--------------------------------------------------------------------------*/ #define hypre_StructStencilShape(stencil) ((stencil) -> shape) #define hypre_StructStencilSize(stencil) ((stencil) -> size) #define hypre_StructStencilNDim(stencil) ((stencil) -> ndim) #define hypre_StructStencilRefCount(stencil) ((stencil) -> ref_count) #define hypre_StructStencilElement(stencil, i) hypre_StructStencilShape(stencil)[i] #endif /****************************************************************************** * 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) ******************************************************************************/ #ifndef hypre_COMMUNICATION_HEADER #define hypre_COMMUNICATION_HEADER /*-------------------------------------------------------------------------- * hypre_CommInfo: * * For "reverse" communication, the following are not needed (may be NULL) * send_rboxnums, send_rboxes, send_transforms * * For "forward" communication, the following are not needed (may be NULL) * recv_rboxnums, recv_rboxes, recv_transforms * *--------------------------------------------------------------------------*/ typedef struct hypre_CommInfo_struct { HYPRE_Int ndim; hypre_BoxArrayArray *send_boxes; hypre_Index send_stride; HYPRE_Int **send_processes; HYPRE_Int **send_rboxnums; hypre_BoxArrayArray *send_rboxes; /* send_boxes, some with periodic shift */ hypre_BoxArrayArray *recv_boxes; hypre_Index recv_stride; HYPRE_Int **recv_processes; HYPRE_Int **recv_rboxnums; hypre_BoxArrayArray *recv_rboxes; /* recv_boxes, some with periodic shift */ HYPRE_Int num_transforms; /* may be 0 = identity transform */ hypre_Index *coords; /* may be NULL = identity transform */ hypre_Index *dirs; /* may be NULL = identity transform */ HYPRE_Int **send_transforms; /* may be NULL = identity transform */ HYPRE_Int **recv_transforms; /* may be NULL = identity transform */ HYPRE_Int boxes_match; /* true (>0) if each send box has a * matching box on the recv processor */ } hypre_CommInfo; /*-------------------------------------------------------------------------- * hypre_CommEntryType: *--------------------------------------------------------------------------*/ typedef struct hypre_CommEntryType_struct { HYPRE_Int offset; /* offset for the data */ HYPRE_Int dim; /* dimension of the communication */ HYPRE_Int length_array[HYPRE_MAXDIM]; /* last dim has length num_values */ HYPRE_Int stride_array[HYPRE_MAXDIM+1]; HYPRE_Int *order; /* order of last dim values */ } hypre_CommEntryType; /*-------------------------------------------------------------------------- * hypre_CommType: *--------------------------------------------------------------------------*/ typedef struct hypre_CommType_struct { HYPRE_Int proc; HYPRE_Int bufsize; /* message buffer size (in doubles) */ HYPRE_Int num_entries; hypre_CommEntryType *entries; /* this is only needed until first send buffer prefix is packed */ HYPRE_Int *rem_boxnums; /* entry remote box numbers */ hypre_Box *rem_boxes; /* entry remote boxes */ } hypre_CommType; /*-------------------------------------------------------------------------- * hypre_CommPkg: * Structure containing information for doing communications *--------------------------------------------------------------------------*/ typedef struct hypre_CommPkg_struct { MPI_Comm comm; HYPRE_Int first_comm; /* is this the first communication? */ HYPRE_Int ndim; HYPRE_Int num_values; hypre_Index send_stride; hypre_Index recv_stride; HYPRE_Int send_bufsize; /* total send buffer size (in doubles) */ HYPRE_Int recv_bufsize; /* total recv buffer size (in doubles) */ HYPRE_Int num_sends; HYPRE_Int num_recvs; hypre_CommType *send_types; hypre_CommType *recv_types; hypre_CommType *copy_from_type; hypre_CommType *copy_to_type; /* these pointers are just to help free up memory for send/from types */ hypre_CommEntryType *entries; HYPRE_Int *rem_boxnums; hypre_Box *rem_boxes; HYPRE_Int num_orders; HYPRE_Int **orders; /* num_orders x num_values */ HYPRE_Int *recv_data_offsets; /* offsets into recv data (by box) */ hypre_BoxArray *recv_data_space; /* recv data dimensions (by box) */ hypre_Index identity_coord; hypre_Index identity_dir; HYPRE_Int *identity_order; } hypre_CommPkg; /*-------------------------------------------------------------------------- * CommHandle: *--------------------------------------------------------------------------*/ typedef struct hypre_CommHandle_struct { hypre_CommPkg *comm_pkg; HYPRE_Complex *send_data; HYPRE_Complex *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; hypre_MPI_Status *status; HYPRE_Complex **send_buffers; HYPRE_Complex **recv_buffers; HYPRE_Complex **send_buffers_data; HYPRE_Complex **recv_buffers_data; /* set = 0, add = 1 */ HYPRE_Int action; } hypre_CommHandle; /*-------------------------------------------------------------------------- * Accessor macros: hypre_CommInto *--------------------------------------------------------------------------*/ #define hypre_CommInfoNDim(info) (info -> ndim) #define hypre_CommInfoSendBoxes(info) (info -> send_boxes) #define hypre_CommInfoSendStride(info) (info -> send_stride) #define hypre_CommInfoSendProcesses(info) (info -> send_processes) #define hypre_CommInfoSendRBoxnums(info) (info -> send_rboxnums) #define hypre_CommInfoSendRBoxes(info) (info -> send_rboxes) #define hypre_CommInfoRecvBoxes(info) (info -> recv_boxes) #define hypre_CommInfoRecvStride(info) (info -> recv_stride) #define hypre_CommInfoRecvProcesses(info) (info -> recv_processes) #define hypre_CommInfoRecvRBoxnums(info) (info -> recv_rboxnums) #define hypre_CommInfoRecvRBoxes(info) (info -> recv_rboxes) #define hypre_CommInfoNumTransforms(info) (info -> num_transforms) #define hypre_CommInfoCoords(info) (info -> coords) #define hypre_CommInfoDirs(info) (info -> dirs) #define hypre_CommInfoSendTransforms(info) (info -> send_transforms) #define hypre_CommInfoRecvTransforms(info) (info -> recv_transforms) #define hypre_CommInfoBoxesMatch(info) (info -> boxes_match) /*-------------------------------------------------------------------------- * Accessor macros: hypre_CommEntryType *--------------------------------------------------------------------------*/ #define hypre_CommEntryTypeOffset(entry) (entry -> offset) #define hypre_CommEntryTypeDim(entry) (entry -> dim) #define hypre_CommEntryTypeLengthArray(entry) (entry -> length_array) #define hypre_CommEntryTypeStrideArray(entry) (entry -> stride_array) #define hypre_CommEntryTypeOrder(entry) (entry -> order) /*-------------------------------------------------------------------------- * Accessor macros: hypre_CommType *--------------------------------------------------------------------------*/ #define hypre_CommTypeProc(type) (type -> proc) #define hypre_CommTypeBufsize(type) (type -> bufsize) #define hypre_CommTypeNumEntries(type) (type -> num_entries) #define hypre_CommTypeEntries(type) (type -> entries) #define hypre_CommTypeEntry(type, i) &(type -> entries[i]) #define hypre_CommTypeRemBoxnums(type) (type -> rem_boxnums) #define hypre_CommTypeRemBoxnum(type, i) (type -> rem_boxnums[i]) #define hypre_CommTypeRemBoxes(type) (type -> rem_boxes) #define hypre_CommTypeRemBox(type, i) &(type -> rem_boxes[i]) /*-------------------------------------------------------------------------- * Accessor macros: hypre_CommPkg *--------------------------------------------------------------------------*/ #define hypre_CommPkgComm(comm_pkg) (comm_pkg -> comm) #define hypre_CommPkgFirstComm(comm_pkg) (comm_pkg -> first_comm) #define hypre_CommPkgNDim(comm_pkg) (comm_pkg -> ndim) #define hypre_CommPkgNumValues(comm_pkg) (comm_pkg -> num_values) #define hypre_CommPkgSendStride(comm_pkg) (comm_pkg -> send_stride) #define hypre_CommPkgRecvStride(comm_pkg) (comm_pkg -> recv_stride) #define hypre_CommPkgSendBufsize(comm_pkg) (comm_pkg -> send_bufsize) #define hypre_CommPkgRecvBufsize(comm_pkg) (comm_pkg -> recv_bufsize) #define hypre_CommPkgNumSends(comm_pkg) (comm_pkg -> num_sends) #define hypre_CommPkgNumRecvs(comm_pkg) (comm_pkg -> num_recvs) #define hypre_CommPkgSendTypes(comm_pkg) (comm_pkg -> send_types) #define hypre_CommPkgSendType(comm_pkg, i) &(comm_pkg -> send_types[i]) #define hypre_CommPkgRecvTypes(comm_pkg) (comm_pkg -> recv_types) #define hypre_CommPkgRecvType(comm_pkg, i) &(comm_pkg -> recv_types[i]) #define hypre_CommPkgCopyFromType(comm_pkg) (comm_pkg -> copy_from_type) #define hypre_CommPkgCopyToType(comm_pkg) (comm_pkg -> copy_to_type) #define hypre_CommPkgEntries(comm_pkg) (comm_pkg -> entries) #define hypre_CommPkgRemBoxnums(comm_pkg) (comm_pkg -> rem_boxnums) #define hypre_CommPkgRemBoxes(comm_pkg) (comm_pkg -> rem_boxes) #define hypre_CommPkgNumOrders(comm_pkg) (comm_pkg -> num_orders) #define hypre_CommPkgOrders(comm_pkg) (comm_pkg -> orders) #define hypre_CommPkgRecvDataOffsets(comm_pkg) (comm_pkg -> recv_data_offsets) #define hypre_CommPkgRecvDataSpace(comm_pkg) (comm_pkg -> recv_data_space) #define hypre_CommPkgIdentityCoord(comm_pkg) (comm_pkg -> identity_coord) #define hypre_CommPkgIdentityDir(comm_pkg) (comm_pkg -> identity_dir) #define hypre_CommPkgIdentityOrder(comm_pkg) (comm_pkg -> identity_order) /*-------------------------------------------------------------------------- * Accessor macros: hypre_CommHandle *--------------------------------------------------------------------------*/ #define hypre_CommHandleCommPkg(comm_handle) (comm_handle -> comm_pkg) #define hypre_CommHandleSendData(comm_handle) (comm_handle -> send_data) #define hypre_CommHandleRecvData(comm_handle) (comm_handle -> recv_data) #define hypre_CommHandleNumRequests(comm_handle) (comm_handle -> num_requests) #define hypre_CommHandleRequests(comm_handle) (comm_handle -> requests) #define hypre_CommHandleStatus(comm_handle) (comm_handle -> status) #define hypre_CommHandleSendBuffers(comm_handle) (comm_handle -> send_buffers) #define hypre_CommHandleRecvBuffers(comm_handle) (comm_handle -> recv_buffers) #define hypre_CommHandleAction(comm_handle) (comm_handle -> action) #define hypre_CommHandleSendBuffersDevice(comm_handle) (comm_handle -> send_buffers_data) #define hypre_CommHandleRecvBuffersDevice(comm_handle) (comm_handle -> recv_buffers_data) #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for computation * *****************************************************************************/ #ifndef hypre_COMPUTATION_HEADER #define hypre_COMPUTATION_HEADER /*-------------------------------------------------------------------------- * hypre_ComputeInfo: *--------------------------------------------------------------------------*/ typedef struct hypre_ComputeInfo_struct { hypre_CommInfo *comm_info; hypre_BoxArrayArray *indt_boxes; hypre_BoxArrayArray *dept_boxes; hypre_Index stride; } hypre_ComputeInfo; /*-------------------------------------------------------------------------- * hypre_ComputePkg: * Structure containing information for doing computations. *--------------------------------------------------------------------------*/ typedef struct hypre_ComputePkg_struct { hypre_CommPkg *comm_pkg; hypre_BoxArrayArray *indt_boxes; hypre_BoxArrayArray *dept_boxes; hypre_Index stride; hypre_StructGrid *grid; hypre_BoxArray *data_space; HYPRE_Int num_values; } hypre_ComputePkg; /*-------------------------------------------------------------------------- * Accessor macros: hypre_ComputeInfo *--------------------------------------------------------------------------*/ #define hypre_ComputeInfoCommInfo(info) (info -> comm_info) #define hypre_ComputeInfoIndtBoxes(info) (info -> indt_boxes) #define hypre_ComputeInfoDeptBoxes(info) (info -> dept_boxes) #define hypre_ComputeInfoStride(info) (info -> stride) /*-------------------------------------------------------------------------- * Accessor macros: hypre_ComputePkg *--------------------------------------------------------------------------*/ #define hypre_ComputePkgCommPkg(compute_pkg) (compute_pkg -> comm_pkg) #define hypre_ComputePkgIndtBoxes(compute_pkg) (compute_pkg -> indt_boxes) #define hypre_ComputePkgDeptBoxes(compute_pkg) (compute_pkg -> dept_boxes) #define hypre_ComputePkgStride(compute_pkg) (compute_pkg -> stride) #define hypre_ComputePkgGrid(compute_pkg) (compute_pkg -> grid) #define hypre_ComputePkgDataSpace(compute_pkg) (compute_pkg -> data_space) #define hypre_ComputePkgNumValues(compute_pkg) (compute_pkg -> num_values) #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the hypre_StructMatrix structures * *****************************************************************************/ #ifndef hypre_STRUCT_MATRIX_HEADER #define hypre_STRUCT_MATRIX_HEADER /*-------------------------------------------------------------------------- * hypre_StructMatrix: *--------------------------------------------------------------------------*/ typedef struct hypre_StructMatrix_struct { MPI_Comm comm; hypre_StructGrid *grid; hypre_StructStencil *user_stencil; hypre_StructStencil *stencil; HYPRE_Int num_values; /* Number of "stored" coefficients */ hypre_BoxArray *data_space; HYPRE_Complex *data; /* Pointer to variable matrix data */ HYPRE_Complex *data_const; /* Pointer to constant matrix data */ HYPRE_Complex **stencil_data; /* Pointer for each stencil */ HYPRE_Int data_alloced; /* Boolean used for freeing data */ HYPRE_Int data_size; /* Size of variable matrix data */ HYPRE_Int data_const_size; /* Size of constant matrix data */ HYPRE_Int **data_indices; /* num-boxes by stencil-size array of indices into the data array. data_indices[b][s] is the starting index of matrix data corresponding to box b and stencil coefficient s */ HYPRE_Int constant_coefficient; /* normally 0; set to 1 for constant coefficient matrices or 2 for constant coefficient with variable diagonal */ HYPRE_Int symmetric; /* Is the matrix symmetric */ HYPRE_Int *symm_elements; /* Which elements are "symmetric" */ HYPRE_Int num_ghost[2*HYPRE_MAXDIM]; /* Num ghost layers in each direction */ HYPRE_BigInt global_size; /* Total number of nonzero coeffs */ hypre_CommPkg *comm_pkg; /* Info on how to update ghost data */ HYPRE_Int ref_count; } hypre_StructMatrix; /*-------------------------------------------------------------------------- * Accessor macros: hypre_StructMatrix *--------------------------------------------------------------------------*/ #define hypre_StructMatrixComm(matrix) ((matrix) -> comm) #define hypre_StructMatrixGrid(matrix) ((matrix) -> grid) #define hypre_StructMatrixUserStencil(matrix) ((matrix) -> user_stencil) #define hypre_StructMatrixStencil(matrix) ((matrix) -> stencil) #define hypre_StructMatrixNumValues(matrix) ((matrix) -> num_values) #define hypre_StructMatrixDataSpace(matrix) ((matrix) -> data_space) #define hypre_StructMatrixData(matrix) ((matrix) -> data) #define hypre_StructMatrixDataConst(matrix) ((matrix) -> data_const) #define hypre_StructMatrixStencilData(matrix) ((matrix) -> stencil_data) #define hypre_StructMatrixDataAlloced(matrix) ((matrix) -> data_alloced) #define hypre_StructMatrixDataSize(matrix) ((matrix) -> data_size) #define hypre_StructMatrixDataConstSize(matrix) ((matrix) -> data_const_size) #define hypre_StructMatrixDataIndices(matrix) ((matrix) -> data_indices) #define hypre_StructMatrixConstantCoefficient(matrix) ((matrix) -> constant_coefficient) #define hypre_StructMatrixSymmetric(matrix) ((matrix) -> symmetric) #define hypre_StructMatrixSymmElements(matrix) ((matrix) -> symm_elements) #define hypre_StructMatrixNumGhost(matrix) ((matrix) -> num_ghost) #define hypre_StructMatrixGlobalSize(matrix) ((matrix) -> global_size) #define hypre_StructMatrixCommPkg(matrix) ((matrix) -> comm_pkg) #define hypre_StructMatrixRefCount(matrix) ((matrix) -> ref_count) #define hypre_StructMatrixNDim(matrix) \ hypre_StructGridNDim(hypre_StructMatrixGrid(matrix)) #define hypre_StructMatrixBox(matrix, b) \ hypre_BoxArrayBox(hypre_StructMatrixDataSpace(matrix), b) #define hypre_StructMatrixBoxData(matrix, b, s) \ (hypre_StructMatrixStencilData(matrix)[s] + hypre_StructMatrixDataIndices(matrix)[b][s]) #define hypre_StructMatrixBoxDataValue(matrix, b, s, index) \ (hypre_StructMatrixBoxData(matrix, b, s) + \ hypre_BoxIndexRank(hypre_StructMatrixBox(matrix, b), index)) #define hypre_CCStructMatrixBoxDataValue(matrix, b, s, index) \ (hypre_StructMatrixBoxData(matrix, b, s) + \ hypre_CCBoxIndexRank(hypre_StructMatrixBox(matrix, b), index)) #endif /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the hypre_StructVector structures * *****************************************************************************/ #ifndef hypre_STRUCT_VECTOR_HEADER #define hypre_STRUCT_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_StructVector: *--------------------------------------------------------------------------*/ typedef struct hypre_StructVector_struct { MPI_Comm comm; hypre_StructGrid *grid; hypre_BoxArray *data_space; HYPRE_Complex *data; /* Pointer to vector data on device*/ HYPRE_Int data_alloced; /* Boolean used for freeing data */ HYPRE_Int data_size; /* Size of vector data */ HYPRE_Int *data_indices; /* num-boxes array of indices into the data array. data_indices[b] is the starting index of vector data corresponding to box b. */ HYPRE_Int num_ghost[2*HYPRE_MAXDIM]; /* Num ghost layers in each * direction */ HYPRE_Int bghost_not_clear; /* Are boundary ghosts clear? */ HYPRE_BigInt global_size; /* Total number coefficients */ HYPRE_Int ref_count; } hypre_StructVector; /*-------------------------------------------------------------------------- * Accessor macros: hypre_StructVector *--------------------------------------------------------------------------*/ #define hypre_StructVectorComm(vector) ((vector) -> comm) #define hypre_StructVectorGrid(vector) ((vector) -> grid) #define hypre_StructVectorDataSpace(vector) ((vector) -> data_space) #define hypre_StructVectorData(vector) ((vector) -> data) #define hypre_StructVectorDataAlloced(vector) ((vector) -> data_alloced) #define hypre_StructVectorDataSize(vector) ((vector) -> data_size) #define hypre_StructVectorDataIndices(vector) ((vector) -> data_indices) #define hypre_StructVectorNumGhost(vector) ((vector) -> num_ghost) #define hypre_StructVectorBGhostNotClear(vector)((vector) -> bghost_not_clear) #define hypre_StructVectorGlobalSize(vector) ((vector) -> global_size) #define hypre_StructVectorRefCount(vector) ((vector) -> ref_count) #define hypre_StructVectorNDim(vector) \ hypre_StructGridNDim(hypre_StructVectorGrid(vector)) #define hypre_StructVectorBox(vector, b) \ hypre_BoxArrayBox(hypre_StructVectorDataSpace(vector), b) #define hypre_StructVectorBoxData(vector, b) \ (hypre_StructVectorData(vector) + hypre_StructVectorDataIndices(vector)[b]) #define hypre_StructVectorBoxDataValue(vector, b, index) \ (hypre_StructVectorBoxData(vector, b) + \ hypre_BoxIndexRank(hypre_StructVectorBox(vector, b), index)) #endif /****************************************************************************** * 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) ******************************************************************************/ /* assumed_part.c */ HYPRE_Int hypre_APSubdivideRegion ( hypre_Box *region , HYPRE_Int dim , HYPRE_Int level , hypre_BoxArray *box_array , HYPRE_Int *num_new_boxes ); HYPRE_Int hypre_APFindMyBoxesInRegions ( hypre_BoxArray *region_array , hypre_BoxArray *my_box_array , HYPRE_Int **p_count_array , HYPRE_Real **p_vol_array ); HYPRE_Int hypre_APGetAllBoxesInRegions ( hypre_BoxArray *region_array , hypre_BoxArray *my_box_array , HYPRE_Int **p_count_array , HYPRE_Real **p_vol_array , MPI_Comm comm ); HYPRE_Int hypre_APShrinkRegions ( hypre_BoxArray *region_array , hypre_BoxArray *my_box_array , MPI_Comm comm ); HYPRE_Int hypre_APPruneRegions ( hypre_BoxArray *region_array , HYPRE_Int **p_count_array , HYPRE_Real **p_vol_array ); HYPRE_Int hypre_APRefineRegionsByVol ( hypre_BoxArray *region_array , HYPRE_Real *vol_array , HYPRE_Int max_regions , HYPRE_Real gamma , HYPRE_Int dim , HYPRE_Int *return_code , MPI_Comm comm ); HYPRE_Int hypre_StructAssumedPartitionCreate ( HYPRE_Int dim , hypre_Box *bounding_box , HYPRE_Real global_boxes_size , HYPRE_Int global_num_boxes , hypre_BoxArray *local_boxes , HYPRE_Int *local_boxnums , HYPRE_Int max_regions , HYPRE_Int max_refinements , HYPRE_Real gamma , MPI_Comm comm , hypre_StructAssumedPart **p_assumed_partition ); HYPRE_Int hypre_StructAssumedPartitionDestroy ( hypre_StructAssumedPart *assumed_part ); HYPRE_Int hypre_APFillResponseStructAssumedPart ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); HYPRE_Int hypre_StructAssumedPartitionGetRegionsFromProc ( hypre_StructAssumedPart *assumed_part , HYPRE_Int proc_id , hypre_BoxArray *assumed_regions ); HYPRE_Int hypre_StructAssumedPartitionGetProcsFromBox ( hypre_StructAssumedPart *assumed_part , hypre_Box *box , HYPRE_Int *num_proc_array , HYPRE_Int *size_alloc_proc_array , HYPRE_Int **p_proc_array ); /* box_algebra.c */ HYPRE_Int hypre_IntersectBoxes ( hypre_Box *box1 , hypre_Box *box2 , hypre_Box *ibox ); HYPRE_Int hypre_SubtractBoxes ( hypre_Box *box1 , hypre_Box *box2 , hypre_BoxArray *box_array ); HYPRE_Int hypre_SubtractBoxArrays ( hypre_BoxArray *box_array1 , hypre_BoxArray *box_array2 , hypre_BoxArray *tmp_box_array ); HYPRE_Int hypre_UnionBoxes ( hypre_BoxArray *boxes ); HYPRE_Int hypre_MinUnionBoxes ( hypre_BoxArray *boxes ); /* box_boundary.c */ HYPRE_Int hypre_BoxBoundaryIntersect ( hypre_Box *box , hypre_StructGrid *grid , HYPRE_Int d , HYPRE_Int dir , hypre_BoxArray *boundary ); HYPRE_Int hypre_BoxBoundaryG ( hypre_Box *box , hypre_StructGrid *g , hypre_BoxArray *boundary ); HYPRE_Int hypre_BoxBoundaryDG ( hypre_Box *box , hypre_StructGrid *g , hypre_BoxArray *boundarym , hypre_BoxArray *boundaryp , HYPRE_Int d ); HYPRE_Int hypre_GeneralBoxBoundaryIntersect( hypre_Box *box, hypre_StructGrid *grid, hypre_Index stencil_element, hypre_BoxArray *boundary ); /* box.c */ HYPRE_Int hypre_SetIndex ( hypre_Index index , HYPRE_Int val ); HYPRE_Int hypre_CopyIndex( hypre_Index in_index , hypre_Index out_index ); HYPRE_Int hypre_CopyToCleanIndex( hypre_Index in_index , HYPRE_Int ndim , hypre_Index out_index ); HYPRE_Int hypre_IndexEqual ( hypre_Index index , HYPRE_Int val , HYPRE_Int ndim ); HYPRE_Int hypre_IndexMin( hypre_Index index , HYPRE_Int ndim ); HYPRE_Int hypre_IndexMax( hypre_Index index , HYPRE_Int ndim ); HYPRE_Int hypre_AddIndexes ( hypre_Index index1 , hypre_Index index2 , HYPRE_Int ndim , hypre_Index result ); HYPRE_Int hypre_SubtractIndexes ( hypre_Index index1 , hypre_Index index2 , HYPRE_Int ndim , hypre_Index result ); HYPRE_Int hypre_IndexesEqual ( hypre_Index index1 , hypre_Index index2 , HYPRE_Int ndim ); hypre_Box *hypre_BoxCreate ( HYPRE_Int ndim ); HYPRE_Int hypre_BoxDestroy ( hypre_Box *box ); HYPRE_Int hypre_BoxInit( hypre_Box *box , HYPRE_Int ndim ); HYPRE_Int hypre_BoxSetExtents ( hypre_Box *box , hypre_Index imin , hypre_Index imax ); HYPRE_Int hypre_CopyBox( hypre_Box *box1 , hypre_Box *box2 ); hypre_Box *hypre_BoxDuplicate ( hypre_Box *box ); HYPRE_Int hypre_BoxVolume( hypre_Box *box ); HYPRE_Real hypre_doubleBoxVolume( hypre_Box *box ); HYPRE_Int hypre_IndexInBox ( hypre_Index index , hypre_Box *box ); HYPRE_Int hypre_BoxGetSize ( hypre_Box *box , hypre_Index size ); HYPRE_Int hypre_BoxGetStrideSize ( hypre_Box *box , hypre_Index stride , hypre_Index size ); HYPRE_Int hypre_BoxGetStrideVolume ( hypre_Box *box , hypre_Index stride , HYPRE_Int *volume_ptr ); HYPRE_Int hypre_BoxIndexRank( hypre_Box *box , hypre_Index index ); HYPRE_Int hypre_BoxRankIndex( hypre_Box *box , HYPRE_Int rank , hypre_Index index ); HYPRE_Int hypre_BoxOffsetDistance( hypre_Box *box , hypre_Index index ); HYPRE_Int hypre_BoxShiftPos( hypre_Box *box , hypre_Index shift ); HYPRE_Int hypre_BoxShiftNeg( hypre_Box *box , hypre_Index shift ); HYPRE_Int hypre_BoxGrowByIndex( hypre_Box *box , hypre_Index index ); HYPRE_Int hypre_BoxGrowByValue( hypre_Box *box , HYPRE_Int val ); HYPRE_Int hypre_BoxGrowByArray ( hypre_Box *box , HYPRE_Int *array ); hypre_BoxArray *hypre_BoxArrayCreate ( HYPRE_Int size , HYPRE_Int ndim ); HYPRE_Int hypre_BoxArrayDestroy ( hypre_BoxArray *box_array ); HYPRE_Int hypre_BoxArraySetSize ( hypre_BoxArray *box_array , HYPRE_Int size ); hypre_BoxArray *hypre_BoxArrayDuplicate ( hypre_BoxArray *box_array ); HYPRE_Int hypre_AppendBox ( hypre_Box *box , hypre_BoxArray *box_array ); HYPRE_Int hypre_DeleteBox ( hypre_BoxArray *box_array , HYPRE_Int index ); HYPRE_Int hypre_DeleteMultipleBoxes ( hypre_BoxArray *box_array , HYPRE_Int *indices , HYPRE_Int num ); HYPRE_Int hypre_AppendBoxArray ( hypre_BoxArray *box_array_0 , hypre_BoxArray *box_array_1 ); hypre_BoxArrayArray *hypre_BoxArrayArrayCreate ( HYPRE_Int size , HYPRE_Int ndim ); HYPRE_Int hypre_BoxArrayArrayDestroy ( hypre_BoxArrayArray *box_array_array ); hypre_BoxArrayArray *hypre_BoxArrayArrayDuplicate ( hypre_BoxArrayArray *box_array_array ); /* box_manager.c */ HYPRE_Int hypre_BoxManEntryGetInfo ( hypre_BoxManEntry *entry , void **info_ptr ); HYPRE_Int hypre_BoxManEntryGetExtents ( hypre_BoxManEntry *entry , hypre_Index imin , hypre_Index imax ); HYPRE_Int hypre_BoxManEntryCopy ( hypre_BoxManEntry *fromentry , hypre_BoxManEntry *toentry ); HYPRE_Int hypre_BoxManSetAllGlobalKnown ( hypre_BoxManager *manager , HYPRE_Int known ); HYPRE_Int hypre_BoxManGetAllGlobalKnown ( hypre_BoxManager *manager , HYPRE_Int *known ); HYPRE_Int hypre_BoxManSetIsEntriesSort ( hypre_BoxManager *manager , HYPRE_Int is_sort ); HYPRE_Int hypre_BoxManGetIsEntriesSort ( hypre_BoxManager *manager , HYPRE_Int *is_sort ); HYPRE_Int hypre_BoxManGetGlobalIsGatherCalled ( hypre_BoxManager *manager , MPI_Comm comm , HYPRE_Int *is_gather ); HYPRE_Int hypre_BoxManGetAssumedPartition ( hypre_BoxManager *manager , hypre_StructAssumedPart **assumed_partition ); HYPRE_Int hypre_BoxManSetAssumedPartition ( hypre_BoxManager *manager , hypre_StructAssumedPart *assumed_partition ); HYPRE_Int hypre_BoxManSetBoundingBox ( hypre_BoxManager *manager , hypre_Box *bounding_box ); HYPRE_Int hypre_BoxManSetNumGhost ( hypre_BoxManager *manager , HYPRE_Int *num_ghost ); HYPRE_Int hypre_BoxManDeleteMultipleEntriesAndInfo ( hypre_BoxManager *manager , HYPRE_Int *indices , HYPRE_Int num ); HYPRE_Int hypre_BoxManCreate ( HYPRE_Int max_nentries , HYPRE_Int info_size , HYPRE_Int dim , hypre_Box *bounding_box , MPI_Comm comm , hypre_BoxManager **manager_ptr ); HYPRE_Int hypre_BoxManIncSize ( hypre_BoxManager *manager , HYPRE_Int inc_size ); HYPRE_Int hypre_BoxManDestroy ( hypre_BoxManager *manager ); HYPRE_Int hypre_BoxManAddEntry ( hypre_BoxManager *manager , hypre_Index imin , hypre_Index imax , HYPRE_Int proc_id , HYPRE_Int box_id , void *info ); HYPRE_Int hypre_BoxManGetEntry ( hypre_BoxManager *manager , HYPRE_Int proc , HYPRE_Int id , hypre_BoxManEntry **entry_ptr ); HYPRE_Int hypre_BoxManGetAllEntries ( hypre_BoxManager *manager , HYPRE_Int *num_entries , hypre_BoxManEntry **entries ); HYPRE_Int hypre_BoxManGetAllEntriesBoxes ( hypre_BoxManager *manager , hypre_BoxArray *boxes ); HYPRE_Int hypre_BoxManGetLocalEntriesBoxes ( hypre_BoxManager *manager , hypre_BoxArray *boxes ); HYPRE_Int hypre_BoxManGetAllEntriesBoxesProc ( hypre_BoxManager *manager , hypre_BoxArray *boxes , HYPRE_Int **procs_ptr ); HYPRE_Int hypre_BoxManGatherEntries ( hypre_BoxManager *manager , hypre_Index imin , hypre_Index imax ); HYPRE_Int hypre_BoxManAssemble ( hypre_BoxManager *manager ); HYPRE_Int hypre_BoxManIntersect ( hypre_BoxManager *manager , hypre_Index ilower , hypre_Index iupper , hypre_BoxManEntry ***entries_ptr , HYPRE_Int *nentries_ptr ); HYPRE_Int hypre_FillResponseBoxManAssemble1 ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); HYPRE_Int hypre_FillResponseBoxManAssemble2 ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); /* communication_info.c */ HYPRE_Int hypre_CommInfoCreate ( hypre_BoxArrayArray *send_boxes , hypre_BoxArrayArray *recv_boxes , HYPRE_Int **send_procs , HYPRE_Int **recv_procs , HYPRE_Int **send_rboxnums , HYPRE_Int **recv_rboxnums , hypre_BoxArrayArray *send_rboxes , hypre_BoxArrayArray *recv_rboxes , HYPRE_Int boxes_match , hypre_CommInfo **comm_info_ptr ); HYPRE_Int hypre_CommInfoSetTransforms ( hypre_CommInfo *comm_info , HYPRE_Int num_transforms , hypre_Index *coords , hypre_Index *dirs , HYPRE_Int **send_transforms , HYPRE_Int **recv_transforms ); HYPRE_Int hypre_CommInfoGetTransforms ( hypre_CommInfo *comm_info , HYPRE_Int *num_transforms , hypre_Index **coords , hypre_Index **dirs ); HYPRE_Int hypre_CommInfoProjectSend ( hypre_CommInfo *comm_info , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_CommInfoProjectRecv ( hypre_CommInfo *comm_info , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_CommInfoDestroy ( hypre_CommInfo *comm_info ); HYPRE_Int hypre_CreateCommInfoFromStencil ( hypre_StructGrid *grid , hypre_StructStencil *stencil , hypre_CommInfo **comm_info_ptr ); HYPRE_Int hypre_CreateCommInfoFromNumGhost ( hypre_StructGrid *grid , HYPRE_Int *num_ghost , hypre_CommInfo **comm_info_ptr ); HYPRE_Int hypre_CreateCommInfoFromGrids ( hypre_StructGrid *from_grid , hypre_StructGrid *to_grid , hypre_CommInfo **comm_info_ptr ); /* computation.c */ HYPRE_Int hypre_ComputeInfoCreate ( hypre_CommInfo *comm_info , hypre_BoxArrayArray *indt_boxes , hypre_BoxArrayArray *dept_boxes , hypre_ComputeInfo **compute_info_ptr ); HYPRE_Int hypre_ComputeInfoProjectSend ( hypre_ComputeInfo *compute_info , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_ComputeInfoProjectRecv ( hypre_ComputeInfo *compute_info , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_ComputeInfoProjectComp ( hypre_ComputeInfo *compute_info , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_ComputeInfoDestroy ( hypre_ComputeInfo *compute_info ); HYPRE_Int hypre_CreateComputeInfo ( hypre_StructGrid *grid , hypre_StructStencil *stencil , hypre_ComputeInfo **compute_info_ptr ); HYPRE_Int hypre_ComputePkgCreate ( hypre_ComputeInfo *compute_info , hypre_BoxArray *data_space , HYPRE_Int num_values , hypre_StructGrid *grid , hypre_ComputePkg **compute_pkg_ptr ); HYPRE_Int hypre_ComputePkgDestroy ( hypre_ComputePkg *compute_pkg ); HYPRE_Int hypre_InitializeIndtComputations ( hypre_ComputePkg *compute_pkg , HYPRE_Complex *data , hypre_CommHandle **comm_handle_ptr ); HYPRE_Int hypre_FinalizeIndtComputations ( hypre_CommHandle *comm_handle ); /* HYPRE_struct_grid.c */ HYPRE_Int HYPRE_StructGridCreate ( MPI_Comm comm , HYPRE_Int dim , HYPRE_StructGrid *grid ); HYPRE_Int HYPRE_StructGridDestroy ( HYPRE_StructGrid grid ); HYPRE_Int HYPRE_StructGridSetExtents ( HYPRE_StructGrid grid , HYPRE_Int *ilower , HYPRE_Int *iupper ); HYPRE_Int HYPRE_StructGridSetPeriodic ( HYPRE_StructGrid grid , HYPRE_Int *periodic ); HYPRE_Int HYPRE_StructGridAssemble ( HYPRE_StructGrid grid ); HYPRE_Int HYPRE_StructGridSetNumGhost ( HYPRE_StructGrid grid , HYPRE_Int *num_ghost ); /* HYPRE_struct_matrix.c */ HYPRE_Int HYPRE_StructMatrixCreate ( MPI_Comm comm , HYPRE_StructGrid grid , HYPRE_StructStencil stencil , HYPRE_StructMatrix *matrix ); HYPRE_Int HYPRE_StructMatrixDestroy ( HYPRE_StructMatrix matrix ); HYPRE_Int HYPRE_StructMatrixInitialize ( HYPRE_StructMatrix matrix ); HYPRE_Int HYPRE_StructMatrixSetValues ( HYPRE_StructMatrix matrix , HYPRE_Int *grid_index , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixGetValues ( HYPRE_StructMatrix matrix , HYPRE_Int *grid_index , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixSetBoxValues ( HYPRE_StructMatrix matrix , HYPRE_Int *ilower , HYPRE_Int *iupper , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixGetBoxValues ( HYPRE_StructMatrix matrix , HYPRE_Int *ilower , HYPRE_Int *iupper , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixSetConstantValues ( HYPRE_StructMatrix matrix , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixAddToValues ( HYPRE_StructMatrix matrix , HYPRE_Int *grid_index , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixAddToBoxValues ( HYPRE_StructMatrix matrix , HYPRE_Int *ilower , HYPRE_Int *iupper , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixAddToConstantValues ( HYPRE_StructMatrix matrix , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructMatrixAssemble ( HYPRE_StructMatrix matrix ); HYPRE_Int HYPRE_StructMatrixSetNumGhost ( HYPRE_StructMatrix matrix , HYPRE_Int *num_ghost ); HYPRE_Int HYPRE_StructMatrixGetGrid ( HYPRE_StructMatrix matrix , HYPRE_StructGrid *grid ); HYPRE_Int HYPRE_StructMatrixSetSymmetric ( HYPRE_StructMatrix matrix , HYPRE_Int symmetric ); HYPRE_Int HYPRE_StructMatrixSetConstantEntries ( HYPRE_StructMatrix matrix , HYPRE_Int nentries , HYPRE_Int *entries ); HYPRE_Int HYPRE_StructMatrixPrint ( const char *filename , HYPRE_StructMatrix matrix , HYPRE_Int all ); HYPRE_Int HYPRE_StructMatrixMatvec ( HYPRE_Complex alpha , HYPRE_StructMatrix A , HYPRE_StructVector x , HYPRE_Complex beta , HYPRE_StructVector y ); HYPRE_Int HYPRE_StructMatrixClearBoundary( HYPRE_StructMatrix matrix ); /* HYPRE_struct_stencil.c */ HYPRE_Int HYPRE_StructStencilCreate ( HYPRE_Int dim , HYPRE_Int size , HYPRE_StructStencil *stencil ); HYPRE_Int HYPRE_StructStencilSetElement ( HYPRE_StructStencil stencil , HYPRE_Int element_index , HYPRE_Int *offset ); HYPRE_Int HYPRE_StructStencilDestroy ( HYPRE_StructStencil stencil ); /* HYPRE_struct_vector.c */ HYPRE_Int HYPRE_StructVectorCreate ( MPI_Comm comm , HYPRE_StructGrid grid , HYPRE_StructVector *vector ); HYPRE_Int HYPRE_StructVectorDestroy ( HYPRE_StructVector struct_vector ); HYPRE_Int HYPRE_StructVectorInitialize ( HYPRE_StructVector vector ); HYPRE_Int HYPRE_StructVectorSetValues ( HYPRE_StructVector vector , HYPRE_Int *grid_index , HYPRE_Complex values ); HYPRE_Int HYPRE_StructVectorSetBoxValues ( HYPRE_StructVector vector , HYPRE_Int *ilower , HYPRE_Int *iupper , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructVectorAddToValues ( HYPRE_StructVector vector , HYPRE_Int *grid_index , HYPRE_Complex values ); HYPRE_Int HYPRE_StructVectorAddToBoxValues ( HYPRE_StructVector vector , HYPRE_Int *ilower , HYPRE_Int *iupper , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructVectorScaleValues ( HYPRE_StructVector vector , HYPRE_Complex factor ); HYPRE_Int HYPRE_StructVectorGetValues ( HYPRE_StructVector vector , HYPRE_Int *grid_index , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructVectorGetBoxValues ( HYPRE_StructVector vector , HYPRE_Int *ilower , HYPRE_Int *iupper , HYPRE_Complex *values ); HYPRE_Int HYPRE_StructVectorAssemble ( HYPRE_StructVector vector ); HYPRE_Int HYPRE_StructVectorPrint ( const char *filename , HYPRE_StructVector vector , HYPRE_Int all ); HYPRE_Int HYPRE_StructVectorSetNumGhost ( HYPRE_StructVector vector , HYPRE_Int *num_ghost ); HYPRE_Int HYPRE_StructVectorCopy ( HYPRE_StructVector x , HYPRE_StructVector y ); HYPRE_Int HYPRE_StructVectorSetConstantValues ( HYPRE_StructVector vector , HYPRE_Complex values ); HYPRE_Int HYPRE_StructVectorGetMigrateCommPkg ( HYPRE_StructVector from_vector , HYPRE_StructVector to_vector , HYPRE_CommPkg *comm_pkg ); HYPRE_Int HYPRE_StructVectorMigrate ( HYPRE_CommPkg comm_pkg , HYPRE_StructVector from_vector , HYPRE_StructVector to_vector ); HYPRE_Int HYPRE_CommPkgDestroy ( HYPRE_CommPkg comm_pkg ); /* project.c */ HYPRE_Int hypre_ProjectBox ( hypre_Box *box , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_ProjectBoxArray ( hypre_BoxArray *box_array , hypre_Index index , hypre_Index stride ); HYPRE_Int hypre_ProjectBoxArrayArray ( hypre_BoxArrayArray *box_array_array , hypre_Index index , hypre_Index stride ); /* struct_axpy.c */ HYPRE_Int hypre_StructAxpy ( HYPRE_Complex alpha , hypre_StructVector *x , hypre_StructVector *y ); /* struct_communication.c */ HYPRE_Int hypre_CommPkgCreate ( hypre_CommInfo *comm_info , hypre_BoxArray *send_data_space , hypre_BoxArray *recv_data_space , HYPRE_Int num_values , HYPRE_Int **orders , HYPRE_Int reverse , MPI_Comm comm , hypre_CommPkg **comm_pkg_ptr ); HYPRE_Int hypre_CommTypeSetEntries ( hypre_CommType *comm_type , HYPRE_Int *boxnums , hypre_Box *boxes , hypre_Index stride , hypre_Index coord , hypre_Index dir , HYPRE_Int *order , hypre_BoxArray *data_space , HYPRE_Int *data_offsets ); HYPRE_Int hypre_CommTypeSetEntry ( hypre_Box *box , hypre_Index stride , hypre_Index coord , hypre_Index dir , HYPRE_Int *order , hypre_Box *data_box , HYPRE_Int data_box_offset , hypre_CommEntryType *comm_entry ); HYPRE_Int hypre_InitializeCommunication ( hypre_CommPkg *comm_pkg , HYPRE_Complex *send_data , HYPRE_Complex *recv_data , HYPRE_Int action , HYPRE_Int tag , hypre_CommHandle **comm_handle_ptr ); HYPRE_Int hypre_FinalizeCommunication ( hypre_CommHandle *comm_handle ); HYPRE_Int hypre_ExchangeLocalData ( hypre_CommPkg *comm_pkg , HYPRE_Complex *send_data , HYPRE_Complex *recv_data , HYPRE_Int action ); HYPRE_Int hypre_CommPkgDestroy ( hypre_CommPkg *comm_pkg ); /* struct_copy.c */ HYPRE_Int hypre_StructCopy ( hypre_StructVector *x , hypre_StructVector *y ); HYPRE_Int hypre_StructPartialCopy ( hypre_StructVector *x , hypre_StructVector *y , hypre_BoxArrayArray *array_boxes ); /* struct_grid.c */ HYPRE_Int hypre_StructGridCreate ( MPI_Comm comm , HYPRE_Int dim , hypre_StructGrid **grid_ptr ); HYPRE_Int hypre_StructGridRef ( hypre_StructGrid *grid , hypre_StructGrid **grid_ref ); HYPRE_Int hypre_StructGridDestroy ( hypre_StructGrid *grid ); HYPRE_Int hypre_StructGridSetPeriodic ( hypre_StructGrid *grid , hypre_Index periodic ); HYPRE_Int hypre_StructGridSetExtents ( hypre_StructGrid *grid , hypre_Index ilower , hypre_Index iupper ); HYPRE_Int hypre_StructGridSetBoxes ( hypre_StructGrid *grid , hypre_BoxArray *boxes ); HYPRE_Int hypre_StructGridSetBoundingBox ( hypre_StructGrid *grid , hypre_Box *new_bb ); HYPRE_Int hypre_StructGridSetIDs ( hypre_StructGrid *grid , HYPRE_Int *ids ); HYPRE_Int hypre_StructGridSetBoxManager ( hypre_StructGrid *grid , hypre_BoxManager *boxman ); HYPRE_Int hypre_StructGridSetMaxDistance ( hypre_StructGrid *grid , hypre_Index dist ); HYPRE_Int hypre_StructGridAssemble ( hypre_StructGrid *grid ); HYPRE_Int hypre_GatherAllBoxes ( MPI_Comm comm , hypre_BoxArray *boxes , HYPRE_Int dim , hypre_BoxArray **all_boxes_ptr , HYPRE_Int **all_procs_ptr , HYPRE_Int *first_local_ptr ); HYPRE_Int hypre_ComputeBoxnums ( hypre_BoxArray *boxes , HYPRE_Int *procs , HYPRE_Int **boxnums_ptr ); HYPRE_Int hypre_StructGridPrint ( FILE *file , hypre_StructGrid *grid ); HYPRE_Int hypre_StructGridRead ( MPI_Comm comm , FILE *file , hypre_StructGrid **grid_ptr ); HYPRE_Int hypre_StructGridSetNumGhost ( hypre_StructGrid *grid , HYPRE_Int *num_ghost ); #if defined(HYPRE_USING_CUDA) HYPRE_Int hypre_StructGridGetMaxBoxSize(hypre_StructGrid *grid); HYPRE_Int hypre_StructGridSetDataLocation( HYPRE_StructGrid grid, HYPRE_Int data_location ); #endif /* struct_innerprod.c */ HYPRE_Real hypre_StructInnerProd ( hypre_StructVector *x , hypre_StructVector *y ); /* struct_io.c */ HYPRE_Int hypre_PrintBoxArrayData ( FILE *file , hypre_BoxArray *box_array , hypre_BoxArray *data_space , HYPRE_Int num_values , HYPRE_Int dim , HYPRE_Complex *data ); HYPRE_Int hypre_PrintCCVDBoxArrayData ( FILE *file , hypre_BoxArray *box_array , hypre_BoxArray *data_space , HYPRE_Int num_values , HYPRE_Int center_rank , HYPRE_Int stencil_size , HYPRE_Int *symm_elements , HYPRE_Int dim , HYPRE_Complex *data ); HYPRE_Int hypre_PrintCCBoxArrayData ( FILE *file , hypre_BoxArray *box_array , hypre_BoxArray *data_space , HYPRE_Int num_values , HYPRE_Complex *data ); HYPRE_Int hypre_ReadBoxArrayData ( FILE *file , hypre_BoxArray *box_array , hypre_BoxArray *data_space , HYPRE_Int num_values , HYPRE_Int dim , HYPRE_Complex *data ); HYPRE_Int hypre_ReadBoxArrayData_CC ( FILE *file , hypre_BoxArray *box_array , hypre_BoxArray *data_space , HYPRE_Int stencil_size , HYPRE_Int real_stencil_size , HYPRE_Int constant_coefficient , HYPRE_Int dim , HYPRE_Complex *data ); /* struct_matrix.c */ HYPRE_Complex *hypre_StructMatrixExtractPointerByIndex ( hypre_StructMatrix *matrix , HYPRE_Int b , hypre_Index index ); hypre_StructMatrix *hypre_StructMatrixCreate ( MPI_Comm comm , hypre_StructGrid *grid , hypre_StructStencil *user_stencil ); hypre_StructMatrix *hypre_StructMatrixRef ( hypre_StructMatrix *matrix ); HYPRE_Int hypre_StructMatrixDestroy ( hypre_StructMatrix *matrix ); HYPRE_Int hypre_StructMatrixInitializeShell ( hypre_StructMatrix *matrix ); HYPRE_Int hypre_StructMatrixInitializeData ( hypre_StructMatrix *matrix , HYPRE_Complex *data ,HYPRE_Complex *data_const); HYPRE_Int hypre_StructMatrixInitialize ( hypre_StructMatrix *matrix ); HYPRE_Int hypre_StructMatrixSetValues ( hypre_StructMatrix *matrix , hypre_Index grid_index , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values , HYPRE_Int action , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructMatrixSetBoxValues ( hypre_StructMatrix *matrix , hypre_Box *set_box , hypre_Box *value_box , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values , HYPRE_Int action , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructMatrixSetConstantValues ( hypre_StructMatrix *matrix , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Complex *values , HYPRE_Int action ); HYPRE_Int hypre_StructMatrixClearValues ( hypre_StructMatrix *matrix , hypre_Index grid_index , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructMatrixClearBoxValues ( hypre_StructMatrix *matrix , hypre_Box *clear_box , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructMatrixAssemble ( hypre_StructMatrix *matrix ); HYPRE_Int hypre_StructMatrixSetNumGhost ( hypre_StructMatrix *matrix , HYPRE_Int *num_ghost ); HYPRE_Int hypre_StructMatrixSetConstantCoefficient ( hypre_StructMatrix *matrix , HYPRE_Int constant_coefficient ); HYPRE_Int hypre_StructMatrixSetConstantEntries ( hypre_StructMatrix *matrix , HYPRE_Int nentries , HYPRE_Int *entries ); HYPRE_Int hypre_StructMatrixClearGhostValues ( hypre_StructMatrix *matrix ); HYPRE_Int hypre_StructMatrixPrint ( const char *filename , hypre_StructMatrix *matrix , HYPRE_Int all ); HYPRE_Int hypre_StructMatrixMigrate ( hypre_StructMatrix *from_matrix , hypre_StructMatrix *to_matrix ); hypre_StructMatrix *hypre_StructMatrixRead ( MPI_Comm comm , const char *filename , HYPRE_Int *num_ghost ); HYPRE_Int hypre_StructMatrixClearBoundary( hypre_StructMatrix *matrix); /* struct_matrix_mask.c */ hypre_StructMatrix *hypre_StructMatrixCreateMask ( hypre_StructMatrix *matrix , HYPRE_Int num_stencil_indices , HYPRE_Int *stencil_indices ); /* struct_matvec.c */ void *hypre_StructMatvecCreate ( void ); HYPRE_Int hypre_StructMatvecSetup ( void *matvec_vdata , hypre_StructMatrix *A , hypre_StructVector *x ); HYPRE_Int hypre_StructMatvecCompute ( void *matvec_vdata , HYPRE_Complex alpha , hypre_StructMatrix *A , hypre_StructVector *x , HYPRE_Complex beta , hypre_StructVector *y ); HYPRE_Int hypre_StructMatvecCC0 ( HYPRE_Complex alpha , hypre_StructMatrix *A , hypre_StructVector *x , hypre_StructVector *y , hypre_BoxArrayArray *compute_box_aa , hypre_IndexRef stride ); HYPRE_Int hypre_StructMatvecCC1 ( HYPRE_Complex alpha , hypre_StructMatrix *A , hypre_StructVector *x , hypre_StructVector *y , hypre_BoxArrayArray *compute_box_aa , hypre_IndexRef stride ); HYPRE_Int hypre_StructMatvecCC2 ( HYPRE_Complex alpha , hypre_StructMatrix *A , hypre_StructVector *x , hypre_StructVector *y , hypre_BoxArrayArray *compute_box_aa , hypre_IndexRef stride ); HYPRE_Int hypre_StructMatvecDestroy ( void *matvec_vdata ); HYPRE_Int hypre_StructMatvec ( HYPRE_Complex alpha , hypre_StructMatrix *A , hypre_StructVector *x , HYPRE_Complex beta , hypre_StructVector *y ); /* struct_scale.c */ HYPRE_Int hypre_StructScale ( HYPRE_Complex alpha , hypre_StructVector *y ); /* struct_stencil.c */ hypre_StructStencil *hypre_StructStencilCreate ( HYPRE_Int dim , HYPRE_Int size , hypre_Index *shape ); hypre_StructStencil *hypre_StructStencilRef ( hypre_StructStencil *stencil ); HYPRE_Int hypre_StructStencilDestroy ( hypre_StructStencil *stencil ); HYPRE_Int hypre_StructStencilElementRank ( hypre_StructStencil *stencil , hypre_Index stencil_element ); HYPRE_Int hypre_StructStencilSymmetrize ( hypre_StructStencil *stencil , hypre_StructStencil **symm_stencil_ptr , HYPRE_Int **symm_elements_ptr ); /* struct_vector.c */ hypre_StructVector *hypre_StructVectorCreate ( MPI_Comm comm , hypre_StructGrid *grid ); hypre_StructVector *hypre_StructVectorRef ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorDestroy ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorInitializeShell ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorInitializeData ( hypre_StructVector *vector , HYPRE_Complex *data); HYPRE_Int hypre_StructVectorInitialize ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorSetValues ( hypre_StructVector *vector , hypre_Index grid_index , HYPRE_Complex *values , HYPRE_Int action , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructVectorSetBoxValues ( hypre_StructVector *vector , hypre_Box *set_box , hypre_Box *value_box , HYPRE_Complex *values , HYPRE_Int action , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructVectorClearValues ( hypre_StructVector *vector , hypre_Index grid_index , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructVectorClearBoxValues ( hypre_StructVector *vector , hypre_Box *clear_box , HYPRE_Int boxnum , HYPRE_Int outside ); HYPRE_Int hypre_StructVectorClearAllValues ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorSetNumGhost ( hypre_StructVector *vector , HYPRE_Int *num_ghost ); HYPRE_Int hypre_StructVectorSetDataSize(hypre_StructVector *vector , HYPRE_Int *data_size, HYPRE_Int *data_host_size); HYPRE_Int hypre_StructVectorAssemble ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorCopy ( hypre_StructVector *x , hypre_StructVector *y ); HYPRE_Int hypre_StructVectorSetConstantValues ( hypre_StructVector *vector , HYPRE_Complex values ); HYPRE_Int hypre_StructVectorSetFunctionValues ( hypre_StructVector *vector , HYPRE_Complex (*fcn )()); HYPRE_Int hypre_StructVectorClearGhostValues ( hypre_StructVector *vector ); HYPRE_Int hypre_StructVectorClearBoundGhostValues ( hypre_StructVector *vector , HYPRE_Int force ); HYPRE_Int hypre_StructVectorScaleValues ( hypre_StructVector *vector , HYPRE_Complex factor ); hypre_CommPkg *hypre_StructVectorGetMigrateCommPkg ( hypre_StructVector *from_vector , hypre_StructVector *to_vector ); HYPRE_Int hypre_StructVectorMigrate ( hypre_CommPkg *comm_pkg , hypre_StructVector *from_vector , hypre_StructVector *to_vector ); HYPRE_Int hypre_StructVectorPrint ( const char *filename , hypre_StructVector *vector , HYPRE_Int all ); hypre_StructVector *hypre_StructVectorRead ( MPI_Comm comm , const char *filename , HYPRE_Int *num_ghost ); hypre_StructVector *hypre_StructVectorClone ( hypre_StructVector *vector ); #ifdef __cplusplus } #endif #endif
sw-post.c
/* * In this module, we are given the results of a full SW run, * and we compute two things: * * 1. The probability the location produced the read (over all possible alignments). * Currently, we only sum over all alignments respecting the current gaps. * As a result, this is useless to do in letter space, where the mapper * cannot distinguish between errors and SNPs. * * 2. For each output letter, the probability that it is correct. * Only for color space. In letter space, this is given by the base quality value. * * Both are computed as scores. */ #include <assert.h> #include <ctype.h> #include <errno.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <zlib.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include "../common/fasta.h" #include "../common/util.h" #include "../common/sw-post.h" #include "../common/sw-full-common.h" #include "../common/time_counter.h" static int initialized; static double pr_snp; static double pr_xover; static double pr_del_open; static double pr_del_extend; static double pr_ins_open; static double pr_ins_extend; static bool use_read_qvs; static bool use_sanger_qvs; static int default_qual; // if no qvs, use this instead static int qual_vector_offset; // i.e. is there a useless qv for the initial base in cs? static int qual_delta; // how much to subtract from chars to get the int static int init_bp; static int len; //static double neglogsixteenth; //static double neglogfourth; typedef struct column{ double forwards[16]; //we'll misuse this for the viterbi double backwards[16]; double forwscale; //adding numerical stability double backscale; //adding numerical stability int ncols; int nlets; int letssize; int colssize; int* lets; int* cols; double* letserrrate; double* colserrrate; char backpointer[16]; //previous state for viterbi double posterior[4]; int max_posterior; int base_call; } states; static struct column * columns; static int max_len; static uint64_t cells, invocs; static time_counter tc; static int check; #pragma omp threadprivate(initialized,\ pr_snp,pr_xover,pr_del_open,pr_del_extend,pr_ins_open,pr_ins_extend,\ use_read_qvs,use_sanger_qvs,default_qual,qual_vector_offset,qual_delta,\ init_bp,len,columns,max_len,\ tc,cells,invocs,check) /********************************************************************************* * * BEGIN Forward-backward code * *********************************************************************************/ #define left(i) ( ((i) >> 2) & 3) #define right(i) ( (i) & 3) #define MIN2(i,j) ( ((i)< (j))? (i):(j)) /* In order to understand any of the code below, you need to understand color-space; Specifically that LETTER ^ LETTER = COLOR : T (00) ^ C (10) = 2 (10), etc. And that LETTER ^ COLOR = NEXTLETTER: T (00) ^ 3 (11) = A (11). */ /* compute prior probability of the node given the emissions. letters are thought to be at the left "side" of the pair emitted by the node */ double nodePrior(states* allstates, int i, int j) { //i is state, j is node in the state double val = 0; double errrate; int let, col, k; for (k = 0; k < allstates[i].nlets; k++) { let = allstates[i].lets[k]; errrate = allstates[i].letserrrate[k]; if (right(j) == let) { val = val - log(1-errrate); } else { val = val - log(errrate/3.0); } } //fprintf(stderr, "nodeprior: %g", val); for (k = 0; k < allstates[i].ncols; k++) { col = allstates[i].cols[k]; errrate = allstates[i].colserrrate[k]; if ((left(j) ^ right(j)) == col) { val = val - log(1-errrate); } else { val = val - log(errrate/3.0); } //fprintf(stderr, " %g\n", val); } return val; } /* Little helper for debugging */ void printStates(states* allstates, int stateslen, FILE* stream) { int i,j,k; fprintf(stream, "\nCONTIG %d", stateslen); for (i=0; i< stateslen; i++) { fprintf(stream, "\nCOLORS[%d] ",i); for (k = 0; k < allstates[i].ncols; k++) { fprintf(stream, "%d (%g)",allstates[i].cols[k], allstates[i].colserrrate[k]); } } for (i=0; i< stateslen; i++) { fprintf(stream, "\nFORWARDSS[%d] ",i); for (j=0; j< 16; j++) { fprintf(stream, "%.5g ",allstates[i].forwards[j] + allstates[i].forwscale); } } for (i=0; i< stateslen; i++) { fprintf(stream, "\nBACKWARDSS[%d] ",i); for (j=0; j< 16; j++) { fprintf(stream, "%.5g ",allstates[i].backwards[j] + allstates[i].backscale); } } for (i=0; i< stateslen; i++) { fprintf(stream, "\nLETS[%d] ",i); for (k = 0; k < allstates[i].nlets; k++) { fprintf(stream, "%d ",allstates[i].lets[k]); } fprintf(stream, "%c",base_to_char(allstates[i].max_posterior, LETTER_SPACE)); fprintf(stream, " %.5g %.5g %.5g %.5g", allstates[i].posterior[0],allstates[i].posterior[1],allstates[i].posterior[2],allstates[i].posterior[3]); } fprintf(stream, "\n"); } /*maximum posterior traceback */ void post_traceback (states* allstates, int stateslen, double norm_px) { int i = 0, j, maxval; for (i = 0; i < stateslen; i++) { for (j=0; j< 4; j++) allstates[i].posterior[j] = 0; for (j = 0; j < 16; j++) { // fprintf(stderr, "%g %g %g\n",allstates[i].forwards[j], allstates[i].backwards[j], norm_px); allstates[i].posterior[right(j)] += exp(-1 * (allstates[i].forwards[j] + allstates[i].backwards[j] + allstates[i].forwscale + allstates[i].backscale - norm_px)); // fprintf(stderr, "distrib[%d,%d] = %g\n", i,j, exp(-1 * (allstates[i].forwards[j] + allstates[i].backwards[j] + allstates[i].forwscale + allstates[i].backscale - norm_px))); } maxval = 0; for (j=1; j< 4; j++) { // fprintf(stderr, "let_distrib[%d,%d] = %g\n", i,j, distrib[j]); if (allstates[i].posterior[j] >allstates[i].posterior[maxval]) maxval = j; } // fprintf (stderr, "\n"); //if (allstates[i].posterior[maxval] > confrate) { allstates[i].max_posterior = maxval; //} //else { // allstates[i].max_posterior = BASE_N; //} } } /*viterbi traceback */ /* char* vit_traceback (states* allstates, int stateslen) { char* result = (char*) calloc (stateslen + 1, 1); int i,j; int minval, prev; assert(0); // not changed to right letter emission for (i = stateslen -1; i >= 0; i--) { minval = 0; for (j = 0; j< 16; j++) { if (allstates[i].forwards[j] < allstates[i].forwards[minval]) { minval = j; } } prev = allstates[i].backpointer[minval]; if (i && (left(minval) != right (prev))) { fprintf (stderr, "BACKTRACE error %d %d %d\n", i, minval, prev); exit(2); } result[i] = letmap[left(minval)]; } return result; } void viterbi (states* allstates, int stateslen) { int i,j,k,let,col; int minback; double valback; double val; assert(0); // not changed to right letter emission i = 0; for (j = 0; j < 16; j++) { allstates[i].forwards[j] = nodePrior(allstates,i,j); } for (i=1; i < stateslen; i++) { for (j = 0; j < 16; j++) { allstates[i].forwards[j] = nodePrior(allstates,i,j); minback = left(j); for (k = 1; k < 16; k++) { if (left(j) == right(k)) { if (allstates[i-1].forwards[k] < allstates[i-1].forwards[minback]) { minback = k; } } } valback = allstates[i-1].forwards[minback]; allstates[i].forwards[j] += valback; allstates[i].backpointer[j] = minback; } } } */ double do_backwards (states* allstates, int stateslen) { int i,j,k; //,let,col; double val; i = stateslen-1; allstates[i].backscale = 999999999; for (j = 0; j < 16; j++) { allstates[i].backwards[j] = 0; // matei change: bug fix allstates[i].backscale = MIN2 (allstates[i].backscale, allstates[i].backwards[j]); } for (j = 0; j < 16; j++) { allstates[i].backwards[j] -= allstates[i].backscale; } for (i = stateslen-2; i >=0; i--) { allstates[i].backscale = 999999999; memset(allstates[i].backwards, 0, 16 * sizeof(allstates[i].backwards[0])); // matei: bug fix for (j = 0; j < 16; j++) { for (k = 0; k < 16; k++) { if (right(j) == left(k)) { val = nodePrior(allstates,i+1,k); allstates[i].backwards[j] += exp(-1*(val + allstates[i+1].backwards[k])); } } // fprintf(stdout, "bw was [%d, %d] = %g\n", i, j, allstates[i].backwards[j]); allstates[i].backwards[j] = -log(allstates[i].backwards[j]); // + neglogfourth; allstates[i].backscale = MIN2 (allstates[i].backscale, allstates[i].backwards[j]); } for (j = 0; j < 16; j++) { allstates[i].backwards[j] -= allstates[i].backscale; // fprintf(stdout, "bw is [%d, %d] = %g\n", i, j, allstates[i].backwards[j]); } allstates[i].backscale += allstates[i+1].backscale; } val = 0; i = 0; for (j = 0; j < 16; j++) { if (left(j) == init_bp) { // matei change: second letter emission val += exp(-1*(allstates[i].backwards[j] + nodePrior(allstates,i,j))); // + neglogfourth)); } } return -log(val) + allstates[0].backscale; } double do_forwards (states* allstates, int stateslen) { int i,j,k; //,let,col; double val; i = 0; j = 0; allstates[i].forwscale = 999999999; for (j = 0; j < 16; j++) { if (left(j) == init_bp) { // matei change: second letter emission allstates[i].forwards[j] = nodePrior(allstates,i,j); // + neglogfourth; allstates[i].forwscale = MIN2 (allstates[i].forwscale, allstates[i].forwards[j]); } else { allstates[i].forwards[j] = HUGE_VAL; } } for (j = 0; j < 16; j++) { allstates[i].forwards[j] -= allstates[i].forwscale; } for (i=1; i < stateslen; i++) { allstates[i].forwscale = 999999999; memset(allstates[i].forwards, 0, 16 * sizeof(allstates[i].forwards[0])); // matei: bug fix for (j = 0; j < 16; j++) { val = nodePrior(allstates,i,j); for (k = 0; k < 16; k++) { if (left(j) == right(k)) { allstates[i].forwards[j] += exp(-1*(allstates[i-1].forwards[k])); } } allstates[i].forwards[j] = val - log(allstates[i].forwards[j]); //+ neglogfourth; allstates[i].forwscale = MIN2 (allstates[i].forwscale, allstates[i].forwards[j]); } for (j = 0; j < 16; j++) { allstates[i].forwards[j] -= allstates[i].forwscale; } allstates[i].forwscale += allstates[i-1].forwscale; } val = 0; i = stateslen-1; for (j = 0; j < 16; j++) { val += exp(-1*(allstates[i].forwards[j])); // matei change: bug fix } return -log(val)+ allstates[i].forwscale; } double forward_backward (states* allstates, int stateslen) { double no1, no2; no1 = do_forwards(allstates, stateslen); no2 = do_backwards(allstates, stateslen); #ifdef DEBUG_POST_SW fprintf (stderr, "SANITY CHECK: no1 == no2 %g %g\n", no1, no2); #endif // don't really want a hard assert due to precision issues return no1; } /********************************************************************************* * * END Forward-backward code * *********************************************************************************/ int post_sw_setup(int _max_len, double _pr_snp, double _pr_xover, double _pr_del_open, double _pr_del_extend, double _pr_ins_open, double _pr_ins_extend, bool _use_read_qvs, bool _use_sanger_qvs, int _qual_vector_offset, int _qual_delta, bool reset_stats) { assert(0 == BASE_0); assert((BASE_A ^ BASE_C) == BASE_1); assert((BASE_A ^ BASE_G) == BASE_2); assert((BASE_A ^ BASE_T) == BASE_3); assert((BASE_C ^ BASE_G) == BASE_3); assert((BASE_C ^ BASE_T) == BASE_2); assert((BASE_G ^ BASE_T) == BASE_1); pr_snp = _pr_snp; pr_xover = _pr_xover; pr_del_open = _pr_del_open; pr_del_extend = _pr_del_extend; pr_ins_open = _pr_ins_open; pr_ins_extend = _pr_ins_extend; qual_delta = _qual_delta; use_read_qvs = _use_read_qvs; use_sanger_qvs = _use_sanger_qvs; if (!use_read_qvs) { default_qual = qv_from_pr_err(pr_xover); //pr_xover = pr_err_from_qv(default_qual); } else { qual_vector_offset = _qual_vector_offset; } //neglogsixteenth = -log(1.0/16.0); //neglogfourth = -log(1.0/4.0); max_len = _max_len; columns = (struct column *)xmalloc(max_len * sizeof(columns[0])); for (int i = 0; i < max_len; i++) { columns[i].lets = (int *)xmalloc(1 * sizeof(columns[i].lets[0])); columns[i].cols = (int *)xmalloc(1 * sizeof(columns[i].cols[0])); columns[i].letserrrate = (double *)xmalloc(1 * sizeof(columns[i].letserrrate[0])); columns[i].colserrrate = (double *)xmalloc(1 * sizeof(columns[i].colserrrate[0])); } if (reset_stats) { cells = invocs = 0; tc.type = DEF_FAST_TIME_COUNTER; tc.counter = 0; } initialized = 1; check = 0; return 1; } int post_sw_cleanup() { for (int i = 0; i < max_len; i++) { free(columns[i].lets); free(columns[i].cols); free(columns[i].letserrrate); free(columns[i].colserrrate); } free(columns); return 1; } int post_sw_stats(uint64_t * _invocs, uint64_t * _cells, double * _secs) { if (_invocs != NULL) *_invocs = invocs; if (_cells != NULL) *_cells = cells; if (_secs != NULL) *_secs = time_counter_get_secs(&tc); return 1; } /* * Extract genome sequence, read, and qvs of interest. */ static void load_local_vectors(uint32_t * read, int _init_bp, char * qual, struct sw_full_results * sfrp) { int start_run, col; int min_qv; int i, j; start_run = 0; min_qv = 10000; for (j = 0; j < sfrp->read_start; j++) { col = EXTRACT(read, j); if (col == BASE_N) { start_run = BASE_N; min_qv = 0; j = sfrp->read_start; break; } start_run ^= col; if (use_read_qvs) min_qv = MIN(min_qv, (int)qual[qual_vector_offset+j]); } len = 0; for (i = 0; sfrp->dbalign[i] != 0; i++) { if (sfrp->qralign[i] != '-') { // ow, it's a deletion; nothing to do if (sfrp->dbalign[i] != '-') { // MATCH columns[len].nlets = 1; columns[len].lets[0] = fasta_get_initial_base(COLOUR_SPACE, &sfrp->dbalign[i]); // => BASE_A/C/G/T columns[len].letserrrate[0] = pr_snp; } else { columns[len].nlets = 0; } // MATCH or INSERTION columns[len].ncols = 1; col = EXTRACT(read, j); if ((len == 0 && start_run == BASE_N) || col == BASE_N) { //columns[len].ncols = 0; // no emission columns[len].cols[0] = BASE_0; columns[len].colserrrate[0] = .75; } else { columns[len].cols[0] = EXTRACT(read, j) ^ (len == 0? start_run : 0); if (use_read_qvs) { columns[len].colserrrate[0] = pr_err_from_qv((len == 0? MIN(min_qv, (int)qual[qual_vector_offset + j]) : (int)qual[qual_vector_offset + j]) - qual_delta); if (!use_sanger_qvs) { columns[len].colserrrate[0] /= (1 + columns[len].colserrrate[0]); } if (columns[len].colserrrate[0] > .75) columns[len].colserrrate[0] = .75; } else { columns[len].colserrrate[0] = pr_xover; } } columns[len].base_call = char_to_base(sfrp->qralign[i]); assert(base_to_char(columns[len].base_call, LETTER_SPACE) == toupper(sfrp->qralign[i])); len++; j++; } } init_bp = _init_bp; #ifdef DEBUG_POST_SW int _i; fprintf(stderr, "db: "); for (_i = 0; _i < len; _i++) { fprintf(stderr, " %c", columns[_i].nlets > 0 ? base_to_char(columns[_i].lets[0], LETTER_SPACE) : '-'); } fprintf(stderr, "\n"); fprintf(stderr, "qr: %c", base_to_char(init_bp, LETTER_SPACE)); for (_i = 0; _i < len; _i++) { fprintf(stderr, " %c ", (columns[_i].ncols > 0 ? base_to_char(columns[_i].cols[0], COLOUR_SPACE) : '-')); } fprintf(stderr, "\n"); fprintf(stderr, "qv: "); for (_i = 0; _i < len; _i++) { fprintf(stderr, "%3d ", qv_from_pr_err(columns[_i].colserrrate[0])); } fprintf(stderr, "\n"); #endif } static void fix_base_calls(uint32_t * read, struct sw_full_results * sfrp, states* allstates, int stateslen) { int i = 0; int j = 0; int prev_base = init_bp; sfrp->matches = 0; sfrp->mismatches = 0; sfrp->crossovers = 0; while (sfrp->qralign[i] != 0) { if (sfrp->qralign[i] != '-') { // position i in qralign corresponds to pos j in allstates int crt_base = allstates[j].max_posterior; sfrp->qralign[i] = base_to_char(crt_base, LETTER_SPACE); if ((prev_base ^ crt_base) == allstates[j].cols[0]) { sfrp->qralign[i] = toupper(base_to_char(crt_base, LETTER_SPACE)); } else { sfrp->qralign[i] = tolower(base_to_char(crt_base, LETTER_SPACE)); ++(sfrp->crossovers); } if (sfrp->dbalign[i] != '-') { if (toupper(sfrp->dbalign[i]) == toupper(sfrp->qralign[i])) { ++(sfrp->matches); } else { ++(sfrp->mismatches); } } prev_base = crt_base; ++j; } ++i; } assert(j == stateslen); } static void get_base_qualities(struct sw_full_results * sfrp) { int i, k; sfrp->qual = (char *)xmalloc((strlen(sfrp->qralign) + 1) * sizeof(sfrp->qual[0])); for (i = 0, k = 0; sfrp->qralign[i] != 0; i++) { if (sfrp->qralign[i] != '-') { int tmp = columns[k].base_call != BASE_N ? qv_from_pr_corr(columns[k].posterior[columns[k].base_call]) : 0; if (tmp > 40) tmp = 40; sfrp->qual[k] = 33 + tmp; // always 33+ in SAM k++; } } assert(k == len); sfrp->qual[k] = 0; } static double get_posterior(struct sw_full_results * sfrp, double total_score) { int i; double res; res = exp(-total_score); // - len * neglogfourth)); for (i = 0; sfrp->dbalign[i] != 0; i++) { if (sfrp->dbalign[i] == '-') { res *= pr_ins_extend; if (i == 0 || sfrp->dbalign[i-1] != '-') { res *= pr_ins_open; } } else if (sfrp->qralign[i] == '-') { res *= pr_del_extend; if (i == 0 || sfrp->qralign[i-1] != '-') { res *= pr_del_open; } } } return res; } /* * Main method, called after full SW. */ void post_sw(uint32_t * read, int _init_bp, char * qual, struct sw_full_results * sfrp) { double total_score; //llint before = rdtsc(), after; TIME_COUNTER_START(tc); invocs++; assert(sfrp != NULL); assert(sfrp->dbalign != NULL); if (!initialized) abort(); #ifdef DEBUG_POST_SW int _i, _j, _last_base, _new_base; char const * spaces = " "; fprintf(stderr, "Post SW\n"); fprintf(stderr, "dbalign: %s%s\n", spaces + strlen(spaces) - sfrp->read_start - 1, sfrp->dbalign); fprintf(stderr, "qralign: %s%s (offset: %d)\n", spaces + strlen(spaces) - sfrp->read_start - 1, sfrp->qralign, sfrp->read_start); fprintf(stderr, "read cs: %c", base_to_char(_init_bp, LETTER_SPACE)); for (_i = 0, _j = 0; _i < (int)sfrp->read_start + (int)strlen(sfrp->qralign); _i++) { if (_j < sfrp->read_start) { fprintf(stderr, "%c", base_to_char(EXTRACT(read, _j), COLOUR_SPACE)); _j++; } else { if (sfrp->qralign[_i - sfrp->read_start] == '-') { fprintf(stderr, "-"); } else { fprintf(stderr, "%c", base_to_char(EXTRACT(read, _j), COLOUR_SPACE)); _j++; } } } fprintf(stderr, "\n"); fprintf(stderr, "read ls: "); _last_base = _init_bp; for (_i = 0, _j = 0; _i < (int)sfrp->read_start + (int)strlen(sfrp->qralign); _i++) { if (_j < sfrp->read_start) { _new_base = cstols(_last_base, EXTRACT(read, _j), false); fprintf(stderr, "%c", base_to_char(_new_base, LETTER_SPACE)); _last_base = _new_base; _j++; } else { if (sfrp->qralign[_i - sfrp->read_start] == '-') { fprintf(stderr, "-"); } else { _new_base = cstols(_last_base, EXTRACT(read, _j), false); fprintf(stderr, "%c", base_to_char(_new_base, LETTER_SPACE)); _last_base = _new_base; _j++; } } } fprintf(stderr, "\n"); fprintf(stderr, "read qv: "); for (_i = 0, _j = 0; _i < (int)sfrp->read_start + (int)strlen(sfrp->qralign); _i++) { if (_j < sfrp->read_start) { fprintf(stderr, "%c", use_read_qvs? qual[_j] : qual_delta + default_qual); _j++; } else { if (sfrp->qralign[_i - sfrp->read_start] == '-') { fprintf(stderr, " "); } else { fprintf(stderr, "%c", use_read_qvs? qual[_j] : qual_delta + default_qual); _j++; } } } fprintf(stderr, "\n"); #endif load_local_vectors(read, _init_bp, qual, sfrp); total_score = forward_backward(columns, len); post_traceback(columns, len, total_score); fix_base_calls(read, sfrp, columns, len); get_base_qualities(sfrp); sfrp->posterior = get_posterior(sfrp, total_score); #ifdef DEBUG_POST_SW fprintf(stderr, "don: "); for (_i = 0; _i < len; _i++) { fprintf(stderr, " %c", base_to_char(columns[_i].max_posterior, LETTER_SPACE)); } fprintf(stderr, "\n"); fprintf(stderr, "bqv: "); for (_i = 0; _i < len; _i++) { int res = columns[_i].posterior[columns[_i].max_posterior] > 1 - .00000001? 80 : (int)(-10.0*(log(1 - columns[_i].posterior[columns[_i].max_posterior])/log(10.0))); fprintf(stderr, " %3d", res); } fprintf(stderr, "\n"); fprintf(stderr, "qralign: "); for (_i = 0, _j = 0; sfrp->qralign[_i] != 0; _i++) { if (sfrp->qralign[_i] != '-') { fprintf(stderr, " %c", sfrp->qralign[_i]); } } fprintf(stderr, "\n"); fprintf(stderr, "bqv: "); for (_i = 0, _j = 0; sfrp->qralign[_i] != 0; _i++) { if (sfrp->qralign[_i] != '-') { fprintf(stderr, "%3d", (int)(sfrp->qual[_j] - qual_delta)); _j++; } } fprintf(stderr, "\n"); printStates(columns, len, stderr); #endif cells += 16*len; //after = rdtsc(); //ticks += MAX(after - before, 0); TIME_COUNTER_STOP(tc); }
GB_unaryop__lnot_int64_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__lnot_int64_uint16 // op(A') function: GB_tran__lnot_int64_uint16 // C type: int64_t // A type: uint16_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ int64_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 != 0) ; // casting #define GB_CASTING(z, aij) \ int64_t z = (int64_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int64_uint16 ( int64_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__lnot_int64_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
CRSMatrix.h
/** * Copyright (c) 2012, OpenGeoSys Community (http://www.opengeosys.com) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.com/LICENSE.txt * * * \file CRSMatrix.h * * Created on 2011-09-20 by Thomas Fischer */ #ifndef CRSMATRIX_H #define CRSMATRIX_H #include <string> #include <fstream> #include <iostream> #include <cassert> // Base #include <algorithm> #include "BaseLib/CodingTools.h" // MathLib #include "SparseMatrixBase.h" #include "sparse_io.h" #include "amuxCRS.h" #include "../Preconditioner/generateDiagPrecond.h" namespace MathLib { #ifdef MSVC_VER #pragma warning(push) #pragma warning(disable: 4018) #endif template<typename FP_TYPE, typename IDX_TYPE> class CRSMatrix: public SparseMatrixBase<FP_TYPE, IDX_TYPE> { public: CRSMatrix() : _row_ptr(NULL), _col_idx(NULL), _data(NULL) { } explicit CRSMatrix(std::string const &fname) : SparseMatrixBase<FP_TYPE, IDX_TYPE>(), _row_ptr(NULL), _col_idx(NULL), _data(NULL) { std::ifstream in(fname.c_str(), std::ios::in | std::ios::binary); if (in) { CS_read(in, SparseMatrixBase<FP_TYPE, IDX_TYPE>::_n_rows, _row_ptr, _col_idx, _data); SparseMatrixBase<FP_TYPE, IDX_TYPE>::_n_cols = SparseMatrixBase<FP_TYPE, IDX_TYPE>::_n_rows; in.close(); } else { std::cout << "cannot open " << fname << std::endl; } } //CRSMatrix(const CRSMatrix &src) : //SparseMatrixBase<FP_TYPE, IDX_TYPE>(src.getNRows(),src.getNCols()) //{ // _row_ptr = new IDX_TYPE[src.getNRows()]; // for (IDX_TYPE i=0; i<src.getNRows(); i++) // _row_ptr[i] = src._row_ptr[i]; // _col_idx = new IDX_TYPE[src.getNNZ()]; // for (IDX_TYPE i=0; i<src.getNNZ(); i++) // _col_idx[i] = src._col_idx[i]; // _data = new FP_TYPE[src.getNNZ()]; // for (IDX_TYPE i=0; i<src.getNNZ(); i++) // _data[i] = src._data[i]; //} //CRSMatrix& operator=(const CRSMatrix &src) //{ // _n_rows = src._n_rows; // _n_cols = src._n_cols; // _row_ptr = new IDX_TYPE[src.getNRows()]; // for (IDX_TYPE i=0; i<src.getNRows(); i++) // _row_ptr[i] = src._row_ptr[i]; // _col_idx = new IDX_TYPE[src.getNNZ()]; // for (IDX_TYPE i=0; i<src.getNNZ(); i++) // _col_idx[i] = src._col_idx[i]; // _data = new FP_TYPE[src.getNNZ()]; // for (IDX_TYPE i=0; i<src.getNNZ(); i++) // _data[i] = src._data[i]; //} CRSMatrix* clone() { CRSMatrix<FP_TYPE, IDX_TYPE> *obj = new CRSMatrix<FP_TYPE, IDX_TYPE>(MatrixBase<IDX_TYPE>::_n_rows); const IDX_TYPE n_nz = getNNZ(); obj->_row_ptr = new IDX_TYPE[MatrixBase<IDX_TYPE>::_n_rows+1]; obj->_col_idx = new IDX_TYPE[n_nz]; obj->_data = new FP_TYPE[n_nz]; for (IDX_TYPE i=0; i<MatrixBase<IDX_TYPE>::_n_rows+1; i++) obj->_row_ptr[i] = _row_ptr[i]; for (IDX_TYPE i=0; i<n_nz; i++) obj->_col_idx[i] = _col_idx[i]; for (IDX_TYPE i=0; i<n_nz; i++) obj->_data[i] = _data[i]; return obj; } CRSMatrix(IDX_TYPE n, IDX_TYPE *iA, IDX_TYPE *jA, FP_TYPE* A) : SparseMatrixBase<FP_TYPE, IDX_TYPE>(n,n), _row_ptr(iA), _col_idx(jA), _data(A) {} CRSMatrix(IDX_TYPE n1) : SparseMatrixBase<FP_TYPE, IDX_TYPE>(n1, n1), _row_ptr(NULL), _col_idx(NULL), _data(NULL) {} virtual ~CRSMatrix() { delete [] _row_ptr; delete [] _col_idx; delete [] _data; } CRSMatrix<FP_TYPE,IDX_TYPE>& operator= (FP_TYPE a) { for (IDX_TYPE i=0; i<getNNZ(); i++) _data[i] = a; return *this; } virtual void amux(FP_TYPE d, FP_TYPE const * const __restrict__ x, FP_TYPE * __restrict__ y) const { amuxCRS<FP_TYPE, IDX_TYPE>(d, this->getNRows(), _row_ptr, _col_idx, _data, x, y); } virtual void precondApply(FP_TYPE* /*x*/) const {} /** * get the number of non-zero entries * @return number of non-zero entries */ IDX_TYPE getNNZ() const { return _row_ptr[MatrixBase<IDX_TYPE>::_n_rows]; } /** * This method inserts/overwrites a non-zero matrix entry. * Precondition: the entry have to be in the sparsity pattern! * @param row the row number * @param col the column number * @param val the value that should be set at pos row,col * @return a value > 0, if the entry is not contained in the sparsity pattern */ int setValue(IDX_TYPE row, IDX_TYPE col, FP_TYPE val) { assert(0 <= (signed)row && row < MatrixBase<IDX_TYPE>::_n_rows); // linear search - for matrices with many entries per row binary search is much faster const IDX_TYPE idx_end (_row_ptr[row+1]); IDX_TYPE j(_row_ptr[row]), k; while (j<idx_end && (k=_col_idx[j]) <= col) { if (k == col) { _data[j] = val; return 0; } j++; } return 1; } /** * This method adds value val to an existing matrix entry at position row,col. * Precondition: the entry have to be in the sparsity pattern! * @param row the row number * @param col the column number * @param val the value that should be set at pos row,col * @return a value > 0, if the entry is not contained in the sparsity pattern */ int addValue(IDX_TYPE row, IDX_TYPE col, FP_TYPE val) { assert(0 <= (signed)row && row < MatrixBase<IDX_TYPE>::_n_rows); // linear search - for matrices with many entries per row binary search is much faster const IDX_TYPE idx_end (_row_ptr[row+1]); IDX_TYPE j(_row_ptr[row]), k; while (j<idx_end && (k=_col_idx[j]) <= col) { if (k == col) { #ifdef _OPENMP #pragma omp atomic #endif _data[j] += val; return 0; } j++; } return 1; } /** * This is an access operator to a non-zero matrix entry. If the value of * a non-existing matrix entry is requested it will be 0.0 returned. * @param row the row number * @param col the column number * @return The corresponding matrix entry or 0.0. */ double getValue(IDX_TYPE row, IDX_TYPE col) { assert(0 <= (signed)row && row < MatrixBase<IDX_TYPE>::_n_rows); // linear search - for matrices with many entries per row binary search is much faster const IDX_TYPE idx_end (_row_ptr[row+1]); IDX_TYPE j(_row_ptr[row]), k; while (j<idx_end && (k=_col_idx[j]) <= col) { if (k == col) { return _data[j]; } j++; } return 0.0; } /** * This is the constant access operator to a non-zero matrix entry. * Precondition: the entries have to be in the sparsity pattern! * @param row the row number * @param col the column number * @return The corresponding matrix entry. */ FP_TYPE operator() (IDX_TYPE row, IDX_TYPE col) const { assert(0 <= (signed)row && row < MatrixBase<IDX_TYPE>::_n_rows); // linear search - for matrices with many entries per row binary search is much faster const IDX_TYPE idx_end (_row_ptr[row+1]); IDX_TYPE j(_row_ptr[row]), k; while (j<idx_end && (k=_col_idx[j]) <= col) { if (k == col) { return _data[j]; } j++; } return 0.0; } /** * get const access to the row pointer array of CRS matrix * @return the index array _row_ptr */ IDX_TYPE const* getRowPtrArray() const { return _row_ptr; } /** * get const access to the column index array of CRS matrix * @return the index array _col_idx */ IDX_TYPE const* getColIdxArray ()const { return _col_idx; } /** * get the matrix entries within an array of CRS matrix * @return */ FP_TYPE const* getEntryArray() const { return _data; } /** * erase rows and columns from sparse matrix * @param n_rows_cols number of rows / columns to remove * @param rows_cols sorted list of rows/columns that should be removed */ void eraseEntries(IDX_TYPE n_rows_cols, IDX_TYPE const* const rows_cols) { IDX_TYPE n_cols(MatrixBase<IDX_TYPE>::_n_rows); //*** remove the rows removeRows(n_rows_cols, rows_cols); //*** transpose transpose(n_cols); //*** remove columns in original means removing rows in the transposed removeRows(n_rows_cols, rows_cols); //*** transpose again transpose(MatrixBase<IDX_TYPE>::_n_rows); } /** * get the j-th column of the sparse matrix * @param j the column number that should be returned * @param column_entries the column entries (have to be allocated */ void getColumn(IDX_TYPE j, FP_TYPE* column_entries) const { for (IDX_TYPE k(0); k<MatrixBase<IDX_TYPE>::_n_rows; k++) { const IDX_TYPE end_row(_row_ptr[k+1]); IDX_TYPE i(_row_ptr[k+1]); while (i<end_row && _col_idx[i] != j) { i++; } if (i==end_row) { column_entries[k] = 0.0; } else { column_entries[k] = _data[i]; } } } //#ifndef NDEBUG void printMat() const { for (IDX_TYPE k(0); k<MatrixBase<IDX_TYPE>::_n_rows; k++) { std::cout << k << ": " << std::flush; const IDX_TYPE row_end(_row_ptr[k+1]); for (IDX_TYPE j(_row_ptr[k]); j<row_end; j++) { std::cout << _col_idx[j] << " " << std::flush; } std::cout << std::endl; } for (IDX_TYPE k(0); k<getNNZ(); k++) { std::cout << _data[k] << " "; } std::cout << std::endl; } //#endif protected: void removeRows (IDX_TYPE n_rows_cols, IDX_TYPE const*const rows) { //*** determine the number of new rows and the number of entries without the rows const IDX_TYPE n_new_rows(MatrixBase<IDX_TYPE>::_n_rows - n_rows_cols); IDX_TYPE *row_ptr_new(new IDX_TYPE[n_new_rows+1]); row_ptr_new[0] = 0; IDX_TYPE row_cnt (1), erase_row_cnt(0); for (IDX_TYPE k(0); k<MatrixBase<IDX_TYPE>::_n_rows; k++) { if (erase_row_cnt < n_rows_cols) { if (k != rows[erase_row_cnt]) { row_ptr_new[row_cnt] = _row_ptr[k+1] - _row_ptr[k]; row_cnt++; } else { erase_row_cnt++; } } else { row_ptr_new[row_cnt] = _row_ptr[k+1] - _row_ptr[k]; row_cnt++; } } //*** sum up the entries for (IDX_TYPE k(0); k<n_new_rows; k++) { row_ptr_new[k+1] = row_ptr_new[k+1] + row_ptr_new[k]; } //*** create new memory for col_idx and data IDX_TYPE nnz_new(row_ptr_new[n_new_rows]); IDX_TYPE *col_idx_new (new IDX_TYPE[nnz_new]); FP_TYPE *data_new (new FP_TYPE[nnz_new]); //*** copy the entries // initialization IDX_TYPE *row_ptr_new_tmp(new IDX_TYPE[n_new_rows+1]); for (IDX_TYPE k(0); k<=n_new_rows; k++) { row_ptr_new_tmp[k] = row_ptr_new[k]; } erase_row_cnt = 0; row_cnt = 0; // copy column index and data entries for (IDX_TYPE k(0); k<MatrixBase<IDX_TYPE>::_n_rows; k++) { if (erase_row_cnt < n_rows_cols) { if (k != rows[erase_row_cnt]) { const IDX_TYPE end (_row_ptr[k+1]); // walk through row for (IDX_TYPE j(_row_ptr[k]); j<end; j++) { col_idx_new[row_ptr_new_tmp[row_cnt]] = _col_idx[j]; data_new[row_ptr_new_tmp[row_cnt]] = _data[j]; row_ptr_new_tmp[row_cnt]++; } row_cnt++; } else { erase_row_cnt++; } } else { const IDX_TYPE end (_row_ptr[k+1]); // walk through row for (IDX_TYPE j(_row_ptr[k]); j<end; j++) { col_idx_new[row_ptr_new_tmp[row_cnt]] = _col_idx[j]; data_new[row_ptr_new_tmp[row_cnt]] = _data[j]; row_ptr_new_tmp[row_cnt]++; } row_cnt++; } } MatrixBase<IDX_TYPE>::_n_rows -= n_rows_cols; std::swap (row_ptr_new, _row_ptr); std::swap (col_idx_new, _col_idx); std::swap (data_new, _data); delete [] row_ptr_new_tmp; delete [] row_ptr_new; delete [] col_idx_new; delete [] data_new; } void transpose (IDX_TYPE n_cols) { // create a helper array row_ptr_nnz IDX_TYPE *row_ptr_nnz(new IDX_TYPE[n_cols+1]); for (IDX_TYPE k(0); k <= n_cols; k++) { row_ptr_nnz[k] = 0; } // count entries per row in the transposed matrix IDX_TYPE nnz(_row_ptr[MatrixBase<IDX_TYPE>::_n_rows]); for (IDX_TYPE k(0); k < nnz; k++) { row_ptr_nnz[_col_idx[k]]++; } // create row_ptr_trans IDX_TYPE *row_ptr_trans(new IDX_TYPE[n_cols + 1]); row_ptr_trans[0] = 0; for (IDX_TYPE k(0); k < n_cols; k++) { row_ptr_trans[k+1] = row_ptr_trans[k] + row_ptr_nnz[k]; } // make a copy of row_ptr_trans for (IDX_TYPE k(0); k <= n_cols; k++) { row_ptr_nnz[k] = row_ptr_trans[k]; } // create arrays col_idx_trans and data_trans assert(nnz == row_ptr_trans[n_cols]); IDX_TYPE *col_idx_trans(new IDX_TYPE[nnz]); FP_TYPE *data_trans(new FP_TYPE[nnz]); // fill arrays col_idx_trans and data_trans for (IDX_TYPE i(0); i < MatrixBase<IDX_TYPE>::_n_rows; i++) { const IDX_TYPE row_end(_row_ptr[i + 1]); for (IDX_TYPE j(_row_ptr[i]); j < row_end; j++) { const IDX_TYPE k(_col_idx[j]); col_idx_trans[row_ptr_nnz[k]] = i; data_trans[row_ptr_nnz[k]] = _data[j]; row_ptr_nnz[k]++; } } MatrixBase<IDX_TYPE>::_n_rows = n_cols; std::swap(row_ptr_trans, _row_ptr); std::swap(col_idx_trans, _col_idx); std::swap(data_trans, _data); delete[] row_ptr_nnz; delete[] row_ptr_trans; delete[] col_idx_trans; delete[] data_trans; } IDX_TYPE *_row_ptr; IDX_TYPE *_col_idx; FP_TYPE* _data; private: DISALLOW_COPY_AND_ASSIGN(CRSMatrix); }; #ifdef MSVC_VER #pragma warning(pop) #endif } // end namespace MathLib #endif
omp_loop.h
// -*- C++ -*- // Copyright (C) 2007-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/omp_loop.h * @brief Parallelization of embarrassingly parallel execution by * means of an OpenMP for loop. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_OMP_LOOP_H #define _GLIBCXX_PARALLEL_OMP_LOOP_H 1 #include <omp.h> #include <parallel/settings.h> #include <parallel/basic_iterator.h> #include <parallel/base.h> namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using an OpenMP for loop. * * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __o User-supplied functor (comparator, predicate, adding * functor, etc.). * @param __f Functor to @a process an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to @a add a single __result to the already * processed elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template<typename _RAIter, typename _Op, typename _Fu, typename _Red, typename _Result> _Op __for_each_template_random_access_omp_loop(_RAIter __begin, _RAIter __end, _Op __o, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { typedef typename std::iterator_traits<_RAIter>::difference_type _DifferenceType; _DifferenceType __length = __end - __begin; _ThreadIndex __num_threads = __gnu_parallel::min<_DifferenceType> (__get_max_threads(), __length); _Result *__thread_results; # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __thread_results = new _Result[__num_threads]; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __thread_results[__i] = _Result(); } _ThreadIndex __iam = omp_get_thread_num(); #pragma omp for schedule(dynamic, _Settings::get().workstealing_chunk_size) for (_DifferenceType __pos = 0; __pos < __length; ++__pos) __thread_results[__iam] = __r(__thread_results[__iam], __f(__o, __begin+__pos)); } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __output = __r(__output, __thread_results[__i]); delete [] __thread_results; // Points to last element processed (needed as return value for // some algorithms like transform). __f._M_finish_iterator = __begin + __length; return __o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_OMP_LOOP_H */
target_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 // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target simd'}} #pragma omp target simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target simd'}} #pragma omp target simd foo void test_no_clause() { int i; #pragma omp target simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target simd' must be a for loop}} #pragma omp target simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp target 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 target simd' are ignored}} #pragma omp target 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 target simd' are ignored}} #pragma omp target simd; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target simd' are ignored}} #pragma omp target simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target simd' are ignored}} #pragma omp target simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp target 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 target simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target 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 target 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 target simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target 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 target simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target 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 target simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target 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 target simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target simd', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target 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 target simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target 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 target simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target simd', but found only 1}} #pragma omp target 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 target simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target 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 target 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 target 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 target simd collapse(5 - 5) 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 target 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 target simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp target simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target 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 target simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target simd firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target simd firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target simd firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target simd firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target simd firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target 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 target simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp target 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 target simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target 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 target 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 target simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd safelen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp target simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp target simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target 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 target 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 target 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 target simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp target 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 target simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target 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 target 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 target simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp target simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp target simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp target simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target 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 target 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 target 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 target 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 target 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 target simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_nontemporal() { int i; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target simd nontemporal( for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target simd nontemporal(, for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 2 {{expected expression}} #pragma omp target simd nontemporal(, ) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 {{expected expression}} #pragma omp target simd nontemporal() for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 {{expected expression}} #pragma omp target simd nontemporal(int) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} omp50-error@+1 {{expected variable name}} #pragma omp target simd nontemporal(0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp target 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 target simd'}} expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp target 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 target simd'}} expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp target 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 target simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target simd nontemporal(x :) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} #pragma omp target 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 target simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}} #pragma omp target simd nontemporal(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} #pragma omp target simd private(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} #pragma omp target simd nontemporal(x) private(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} #pragma omp target simd nontemporal(x, y : 0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} #pragma omp target simd nontemporal(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp target simd'}} #pragma omp target simd lastprivate(x) nontemporal(x) for (i = 0; i < 16; ++i) ; }
mod.c
#include <math.h> #include <stddef.h> #include "../sailfish.h" // ============================ COMPAT ======================================== // ============================================================================ #ifdef __ROCM__ #include <hip/hip_runtime.h> #endif #if !defined(__NVCC__) && !defined(__ROCM__) #define __device__ #define __host__ #define EXTERN_C #else #define EXTERN_C extern "C" #endif // ============================ PHYSICS ======================================= // ============================================================================ #define NCONS 3 #define PLM_THETA 2.0 #define ADIABATIC_GAMMA (5.0 / 3.0) // ============================ MATH ========================================== // ============================================================================ #define real double #define min2(a, b) ((a) < (b) ? (a) : (b)) #define max2(a, b) ((a) > (b) ? (a) : (b)) #define min3(a, b, c) min2(a, min2(b, c)) #define max3(a, b, c) max2(a, max2(b, c)) #define sign(x) copysign(1.0, x) #define minabs(a, b, c) min3(fabs(a), fabs(b), fabs(c)) static __host__ __device__ real plm_gradient_scalar(real yl, real y0, real yr) { real a = (y0 - yl) * PLM_THETA; real b = (yr - yl) * 0.5; real c = (yr - y0) * PLM_THETA; return 0.25 * fabs(sign(a) + sign(b)) * (sign(a) + sign(c)) * minabs(a, b, c); } static __host__ __device__ void plm_gradient(real *yl, real *y0, real *yr, real *g) { if (yl && y0 && yr) { for (int q = 0; q < NCONS; ++q) { g[q] = plm_gradient_scalar(yl[q], y0[q], yr[q]); } } else { for (int q = 0; q < NCONS; ++q) { g[q] = 0.0; } } } // ============================ HYDRO ========================================= // ============================================================================ static __host__ __device__ void conserved_to_primitive(const real *cons, real *prim) { const real rho = cons[0]; const real px = cons[1]; const real energy = cons[2]; const real vx = px / rho; const real kinetic_energy = 0.5 * rho * vx * vx; const real thermal_energy = energy - kinetic_energy; const real pressure = thermal_energy * (ADIABATIC_GAMMA - 1.0); prim[0] = rho; prim[1] = vx; prim[2] = pressure; } static __device__ __host__ void primitive_to_conserved(const real *prim, real *cons) { const real rho = prim[0]; const real vx = prim[1]; const real pressure = prim[2]; const real px = vx * rho; const real kinetic_energy = 0.5 * rho * vx * vx; const real thermal_energy = pressure / (ADIABATIC_GAMMA - 1.0); cons[0] = rho; cons[1] = px; cons[2] = kinetic_energy + thermal_energy; } static __host__ __device__ void primitive_to_flux(const real *prim, const real *cons, real *flux) { const real vn = prim[1]; const real pressure = prim[2]; flux[0] = vn * cons[0]; flux[1] = vn * cons[1] + pressure; flux[2] = vn * cons[2] + pressure * vn; } static __host__ __device__ real primitive_to_sound_speed_squared(const real *prim) { const real rho = prim[0]; const real pressure = prim[2]; return ADIABATIC_GAMMA * pressure / rho; } static __host__ __device__ void primitive_to_outer_wavespeeds(const real *prim, real *wavespeeds) { const real cs = sqrt(primitive_to_sound_speed_squared(prim)); const real vn = prim[1]; wavespeeds[0] = vn - cs; wavespeeds[1] = vn + cs; } static __host__ __device__ real primitive_to_max_wavespeed(const real *prim) { real cs = sqrt(primitive_to_sound_speed_squared(prim)); real vx = prim[1]; real ax = max2(fabs(vx - cs), fabs(vx + cs)); return ax; } static __host__ __device__ void riemann_hlle(const real *pl, const real *pr, real *flux) { real ul[NCONS]; real ur[NCONS]; real fl[NCONS]; real fr[NCONS]; real al[2]; real ar[2]; primitive_to_conserved(pl, ul); primitive_to_conserved(pr, ur); primitive_to_flux(pl, ul, fl); primitive_to_flux(pr, ur, fr); primitive_to_outer_wavespeeds(pl, al); primitive_to_outer_wavespeeds(pr, ar); const real am = min3(0.0, al[0], ar[0]); const real ap = max3(0.0, al[1], ar[1]); for (int q = 0; q < NCONS; ++q) { flux[q] = (fl[q] * ap - fr[q] * am - (ul[q] - ur[q]) * ap * am) / (ap - am); } } // ============================ PATCH ========================================= // ============================================================================ static __host__ __device__ real face_area(enum Coordinates coords, real x) { switch (coords) { case Cartesian: return 1.0; case SphericalPolar: return x * x; } return 0.0; } static __host__ __device__ real cell_volume(enum Coordinates coords, real x0, real x1) { switch (coords) { case Cartesian: return x1 - x0; case SphericalPolar: return (pow(x1, 3) - pow(x0, 3)) / 3.0; } return 0.0; } static __host__ __device__ void geometric_source_terms(enum Coordinates coords, real x0, real x1, const real *prim, real *source) { switch (coords) { case SphericalPolar: { double p = prim[2]; source[0] = 0.0; source[1] = p * (x1 * x1 - x0 * x0); source[2] = 0.0; break; } default: { source[0] = 0.0; source[1] = 0.0; source[2] = 0.0; } } } // ============================ PATCH ========================================= // ============================================================================ #define FOR_EACH(p) \ for (int i = p.start; i < p.start + p.count; ++i) #define FOR_EACH_OMP(p) \ _Pragma("omp parallel for") \ for (int i = p.start; i < p.start + p.count; ++i) #define GET(p, i) (p.data + p.jumps * ((i) - p.start)) struct Patch { int start; int count; int jumps; int num_fields; real *data; }; static struct Patch patch(int num_elements, int num_fields, real *data) { struct Patch patch; patch.start = 0; patch.count = num_elements; patch.jumps = num_fields; patch.num_fields = num_fields; patch.data = data; return patch; } // ============================ SCHEME ======================================== // ============================================================================ static __host__ __device__ void primitive_to_conserved_zone( struct Patch primitive, struct Patch conserved, int i) { real *p = GET(primitive, i); real *u = GET(conserved, i); primitive_to_conserved(p, u); } static __host__ __device__ void advance_rk_zone( struct Patch face_positions, struct Patch conserved_rk, struct Patch primitive_rd, struct Patch primitive_wr, struct BoundaryCondition bc, enum Coordinates coords, real a, real dt, int i) { if (bc.type == Inflow && i == 0) { return; } int ni = face_positions.count - 1; real xl = *GET(face_positions, i); real xr = *GET(face_positions, i + 1); real *un = GET(conserved_rk, i); real *pcc = GET(primitive_rd, i); real *pli = i >= 0 + 1 ? GET(primitive_rd, i - 1) : NULL; real *pri = i < ni - 1 ? GET(primitive_rd, i + 1) : NULL; real *pki = i >= 0 + 2 ? GET(primitive_rd, i - 2) : NULL; real *pti = i < ni - 2 ? GET(primitive_rd, i + 2) : NULL; real plip[NCONS]; real plim[NCONS]; real prip[NCONS]; real prim[NCONS]; real gxli[NCONS]; real gxri[NCONS]; real gxcc[NCONS]; // NOTE: the gradient calculation here assumes smoothly varying face // separations. Also note plm_gradient initializes the gradients to zero // if any of the inputs are NULL. plm_gradient(pki, pli, pcc, gxli); plm_gradient(pli, pcc, pri, gxcc); plm_gradient(pcc, pri, pti, gxri); for (int q = 0; q < NCONS; ++q) { plim[q] = pli ? pli[q] + 0.5 * gxli[q] : pcc[q]; plip[q] = pcc[q] - 0.5 * gxcc[q]; prim[q] = pcc[q] + 0.5 * gxcc[q]; prip[q] = pri ? pri[q] - 0.5 * gxri[q] : pcc[q]; } real fli[NCONS]; real fri[NCONS]; real ucc[NCONS]; real sources[NCONS]; real dal = face_area(coords, xl); real dar = face_area(coords, xr); real dv = cell_volume(coords, xl, xr); riemann_hlle(plim, plip, fli); riemann_hlle(prim, prip, fri); primitive_to_conserved(pcc, ucc); geometric_source_terms(coords, xl, xr, pcc, sources); for (int q = 0; q < NCONS; ++q) { ucc[q] += (fli[q] * dal - fri[q] * dar + sources[q]) / dv * dt; ucc[q] = (1.0 - a) * ucc[q] + a * un[q]; } real *pout = GET(primitive_wr, i); conserved_to_primitive(ucc, pout); } static __host__ __device__ void wavespeed_zone( struct Patch primitive, struct Patch wavespeed, int i) { real *pc = GET(primitive, i); real a = primitive_to_max_wavespeed(pc); GET(wavespeed, i)[0] = a; } // ============================ KERNELS ======================================= // ============================================================================ #if defined(__NVCC__) || defined(__ROCM__) static void __global__ primitive_to_conserved_kernel( struct Patch primitive, struct Patch conserved) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i < conserved.count) { primitive_to_conserved_zone(primitive, conserved, i); } } static void __global__ advance_rk_kernel( struct Patch faces, struct Patch conserved_rk, struct Patch primitive_rd, struct Patch primitive_wr, struct BoundaryCondition bc, enum Coordinates coords, real a, real dt) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i < primitive_wr.count) { advance_rk_zone(faces, conserved_rk, primitive_rd, primitive_wr, bc, coords, a, dt, i); } } static void __global__ wavespeed_kernel( struct Patch primitive, struct Patch wavespeed) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i < wavespeed.count) { wavespeed_zone(primitive, wavespeed, i); } } #endif // ============================ PUBLIC API ==================================== // ============================================================================ /** * Converts an array of primitive data to an array of conserved data. The * array index space must follow the descriptions below. * @param faces The faces [ni = num_zones] * @param conserved_ptr[in] [0] [ni] [3] * @param primitive_ptr[out] [0] [ni] [3] * @param mode The execution mode */ EXTERN_C void euler1d_primitive_to_conserved( int num_zones, real *primitive_ptr, real *conserved_ptr, enum ExecutionMode mode) { struct Patch primitive = patch(num_zones, NCONS, primitive_ptr); struct Patch conserved = patch(num_zones, NCONS, conserved_ptr); switch (mode) { case CPU: { FOR_EACH(conserved) { primitive_to_conserved_zone(primitive, conserved, i); } break; } case OMP: { #ifdef _OPENMP FOR_EACH_OMP(conserved) { primitive_to_conserved_zone(primitive, conserved, i); } #endif break; } case GPU: { #if defined(__NVCC__) || defined(__ROCM__) dim3 bs = dim3(256); dim3 bd = dim3((num_zones + bs.x - 1) / bs.x); primitive_to_conserved_kernel<<<bd, bs>>>(primitive, conserved); #endif break; } } } /** * Updates an array of primitive data by advancing it a single Runge-Kutta * step. * @param face_positions_ptr[in] [num_zones + 1] [1] * @param conserved_rk_ptr[in] [num_zones] [3] * @param primitive_rd_ptr[in] [num_zones] [3] * @param primitive_wr_ptr[out] [num_zones] [3] * @param a The RK averaging parameter * @param dt The time step * @param bc The boundary conditions type * @param coords The coordinate system * @param mode The execution mode */ EXTERN_C void euler1d_advance_rk( int num_zones, real *face_positions_ptr, real *conserved_rk_ptr, real *primitive_rd_ptr, real *primitive_wr_ptr, real a, real dt, struct BoundaryCondition bc, enum Coordinates coords, enum ExecutionMode mode) { struct Patch face_positions = patch(num_zones + 1, 1, face_positions_ptr); struct Patch conserved_rk = patch(num_zones, NCONS, conserved_rk_ptr); struct Patch primitive_rd = patch(num_zones, NCONS, primitive_rd_ptr); struct Patch primitive_wr = patch(num_zones, NCONS, primitive_wr_ptr); switch (mode) { case CPU: { FOR_EACH(conserved_rk) { advance_rk_zone(face_positions, conserved_rk, primitive_rd, primitive_wr, bc, coords, a, dt, i); } break; } case OMP: { #ifdef _OPENMP FOR_EACH_OMP(conserved_rk) { advance_rk_zone(face_positions, conserved_rk, primitive_rd, primitive_wr, bc, coords, a, dt, i); } #endif break; } case GPU: { #if defined(__NVCC__) || defined(__ROCM__) dim3 bs = dim3(256); dim3 bd = dim3((num_zones + bs.x - 1) / bs.x); advance_rk_kernel<<<bd, bs>>>(face_positions, conserved_rk, primitive_rd, primitive_wr, bc, coords, a, dt); #endif break; } } } /** * Fill a buffer with the maximum wavespeed in each zone. * @param primitive_ptr[in] [num_zones] [3] * @param wavespeed_ptr[out] [num_zones] [1] * @param mode The execution mode */ EXTERN_C void euler1d_wavespeed( int num_zones, real *primitive_ptr, real *wavespeed_ptr, enum ExecutionMode mode) { struct Patch primitive = patch(num_zones, NCONS, primitive_ptr); struct Patch wavespeed = patch(num_zones, 1, wavespeed_ptr); switch (mode) { case CPU: { FOR_EACH(wavespeed) { wavespeed_zone(primitive, wavespeed, i); } break; } case OMP: { #ifdef _OPENMP FOR_EACH_OMP(wavespeed) { wavespeed_zone(primitive, wavespeed, i); } #endif break; } case GPU: { #if defined(__NVCC__) || defined(__ROCM__) dim3 bs = dim3(256); dim3 bd = dim3((num_zones + bs.x - 1) / bs.x); wavespeed_kernel<<<bd, bs>>>(primitive, wavespeed); #endif break; } } } /** * Return the maximum wavespeed over all zones. Not implemented for GPU * execution. * @param primitive_ptr[in] [num_zones] [3] * @param mode The execution mode */ EXTERN_C real euler1d_max_wavespeed( int num_zones, real *primitive_ptr, enum ExecutionMode mode) { struct Patch primitive = patch(num_zones, NCONS, primitive_ptr); real a_max = 0.0; switch (mode) { case CPU: { for (int i = 0; i < num_zones; ++i) { a_max = max2(a_max, primitive_to_max_wavespeed(GET(primitive, i))); } break; } case OMP: { #ifdef _OPENMP #pragma omp parallel for reduction(max:a_max) for (int i = 0; i < num_zones; ++i) { a_max = max2(a_max, primitive_to_max_wavespeed(GET(primitive, i))); } #endif break; } case GPU: break; // Not implemented, use euler1d_wavespeed // followed by a GPU reduction. } return a_max; }
boxloop_cuda.h
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Header info for the BoxLoop * *****************************************************************************/ /*-------------------------------------------------------------------------- * BoxLoop macros: *--------------------------------------------------------------------------*/ #ifndef HYPRE_NEWBOXLOOP_HEADER #define HYPRE_NEWBOXLOOP_HEADER #define HYPRE_LAMBDA [=] __host__ __device__ #define BLOCKSIZE 512 typedef struct hypre_Boxloop_struct { HYPRE_Int lsize0,lsize1,lsize2; HYPRE_Int strides0,strides1,strides2; HYPRE_Int bstart0,bstart1,bstart2; HYPRE_Int bsize0,bsize1,bsize2; } hypre_Boxloop; #if 1 #define hypre_fence() /*printf("\n hypre_newBoxLoop in %s(%d) function %s\n",__FILE__,__LINE__,__FUNCTION__);*/ #else #define hypre_fence() \ { \ cudaError err = cudaGetLastError(); \ if ( cudaSuccess != err ) \ { \ printf("\n ERROR hypre_newBoxLoop: %s in %s(%d) function %s\n",cudaGetErrorString(err),__FILE__,__LINE__,__FUNCTION__); \ /* HYPRE_Int *p = NULL; *p = 1; */ \ } \ HYPRE_CUDA_CALL( cudaDeviceSynchronize() ); \ } #endif /* #define hypre_reduce_policy cuda_reduce<BLOCKSIZE> */ #ifdef __cplusplus extern "C++" { #endif template <typename LOOP_BODY> __global__ void forall_kernel(LOOP_BODY loop_body, HYPRE_Int length) { HYPRE_Int idx = blockDim.x * blockIdx.x + threadIdx.x; if (idx < length) { loop_body(idx); } } template<typename LOOP_BODY> void BoxLoopforall(HYPRE_ExecutionPolicy policy, HYPRE_Int length, LOOP_BODY loop_body) { if (policy == HYPRE_EXEC_HOST) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (HYPRE_Int idx = 0; idx < length; idx++) { loop_body(idx); } } else if (policy == HYPRE_EXEC_DEVICE) { HYPRE_Int gridSize = (length + BLOCKSIZE - 1) / BLOCKSIZE; const dim3 gDim(gridSize), bDim(BLOCKSIZE); HYPRE_CUDA_LAUNCH( forall_kernel, gDim, bDim, loop_body, length ); } } template <typename LOOP_BODY> __global__ void reductionforall_kernel(LOOP_BODY ReductionLoop, HYPRE_Int length) { ReductionLoop(blockDim.x*blockIdx.x+threadIdx.x, blockDim.x*gridDim.x, length); } template<typename LOOP_BODY> void ReductionBoxLoopforall(HYPRE_ExecutionPolicy policy, HYPRE_Int length, LOOP_BODY ReductionLoop) { if (length <= 0) { return; } if (policy == HYPRE_EXEC_HOST) { hypre_assert(0); } else if (policy == HYPRE_EXEC_DEVICE) { HYPRE_Int gridSize = (length + BLOCKSIZE - 1) / BLOCKSIZE; gridSize = hypre_min(gridSize, 1024); /* hypre_printf("length= %d, blocksize = %d, gridsize = %d\n", length, BLOCKSIZE, gridSize); */ const dim3 gDim(gridSize), bDim(BLOCKSIZE); HYPRE_CUDA_LAUNCH( reductionforall_kernel, gDim, bDim, ReductionLoop, length ); } } #ifdef __cplusplus } #endif #define hypre_BoxLoopIncK(k,box,hypre__i) \ HYPRE_Int hypre_boxD##k = 1; \ HYPRE_Int hypre__i = 0; \ hypre__i += (hypre_IndexD(local_idx, 0)*box.strides0 + box.bstart0) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize0 + 1); \ hypre__i += (hypre_IndexD(local_idx, 1)*box.strides1 + box.bstart1) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize1 + 1); \ hypre__i += (hypre_IndexD(local_idx, 2)*box.strides2 + box.bstart2) * hypre_boxD##k; \ hypre_boxD##k *= hypre_max(0, box.bsize2 + 1); #define hypre_newBoxLoopInit(ndim,loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int hypre_d = 0;hypre_d < ndim;hypre_d ++) \ hypre__tot *= loop_size[hypre_d]; #define hypre_BasicBoxLoopInit(ndim,loop_size) \ HYPRE_Int hypre__tot = 1; \ for (HYPRE_Int hypre_d = 0;hypre_d < ndim;hypre_d ++) \ hypre__tot *= loop_size[hypre_d]; \ #define hypre_newBoxLoopDeclare(box) \ hypre_Index local_idx; \ HYPRE_Int idx_local = idx; \ hypre_IndexD(local_idx, 0) = idx_local % box.lsize0; \ idx_local = idx_local / box.lsize0; \ hypre_IndexD(local_idx, 1) = idx_local % box.lsize1; \ idx_local = idx_local / box.lsize1; \ hypre_IndexD(local_idx, 2) = idx_local % box.lsize2; \ #define hypre_newBoxLoop0Begin(ndim, loop_size) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { #define hypre_newBoxLoop0End() \ }); \ hypre_fence(); \ } #define hypre_BoxLoopDataDeclareK(k,ndim,loop_size,dbox,start,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = start[0] - dbox->imin[0]; \ databox##k.bsize0 = dbox->imax[0]-dbox->imin[0]; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = start[1] - dbox->imin[1]; \ databox##k.bsize1 = dbox->imax[1]-dbox->imin[1]; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = start[2] - dbox->imin[2]; \ databox##k.bsize2 = dbox->imax[2]-dbox->imin[2]; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define hypre_newBoxLoop1Begin(ndim, loop_size, \ dbox1, start1, stride1, i1) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); #define hypre_newBoxLoop1End(i1) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop2Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); #define hypre_newBoxLoop2End(i1, i2) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop3Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ hypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ hypre_BoxLoopIncK(3,databox3,i3); #define hypre_newBoxLoop3End(i1, i2,i3) \ }); \ hypre_fence(); \ } #define hypre_newBoxLoop4Begin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ dbox3, start3, stride3, i3, \ dbox4, start4, stride4, i4) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ hypre_BoxLoopDataDeclareK(3,ndim,loop_size,dbox3,start3,stride3); \ hypre_BoxLoopDataDeclareK(4,ndim,loop_size,dbox4,start4,stride4); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ hypre_BoxLoopIncK(3,databox3,i3); \ hypre_BoxLoopIncK(4,databox4,i4); #define hypre_newBoxLoop4End(i1, i2, i3, i4) \ }); \ hypre_fence(); \ } #define zypre_BasicBoxLoopDataDeclareK(k,ndim,loop_size,stride) \ hypre_Boxloop databox##k; \ databox##k.lsize0 = loop_size[0]; \ databox##k.strides0 = stride[0]; \ databox##k.bstart0 = 0; \ databox##k.bsize0 = 0; \ if (ndim > 1) \ { \ databox##k.lsize1 = loop_size[1]; \ databox##k.strides1 = stride[1]; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ else \ { \ databox##k.lsize1 = 1; \ databox##k.strides1 = 0; \ databox##k.bstart1 = 0; \ databox##k.bsize1 = 0; \ } \ if (ndim == 3) \ { \ databox##k.lsize2 = loop_size[2]; \ databox##k.strides2 = stride[2]; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } \ else \ { \ databox##k.lsize2 = 1; \ databox##k.strides2 = 0; \ databox##k.bstart2 = 0; \ databox##k.bsize2 = 0; \ } #define zypre_newBasicBoxLoop1Begin(ndim, loop_size, \ stride1, i1) \ { \ hypre_BasicBoxLoopInit(ndim,loop_size); \ zypre_BasicBoxLoopDataDeclareK(1,ndim,loop_size,stride1); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ #define zypre_newBasicBoxLoop2Begin(ndim, loop_size, \ stride1, i1, \ stride2, i2) \ { \ hypre_BasicBoxLoopInit(ndim,loop_size); \ zypre_BasicBoxLoopDataDeclareK(1,ndim,loop_size,stride1); \ zypre_BasicBoxLoopDataDeclareK(2,ndim,loop_size,stride2); \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),hypre__tot,HYPRE_LAMBDA (HYPRE_Int idx) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); \ #define hypre_LoopBegin(size,idx) \ { \ BoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()),size,HYPRE_LAMBDA (HYPRE_Int idx) \ { #define hypre_LoopEnd() \ }); \ hypre_fence(); \ } #define hypre_newBoxLoopGetIndex(index) \ index[0] = hypre_IndexD(local_idx, 0); index[1] = hypre_IndexD(local_idx, 1); index[2] = hypre_IndexD(local_idx, 2); #define hypre_BoxLoopBlock() 0 #define hypre_BoxLoop0Begin hypre_newBoxLoop0Begin #define hypre_BoxLoop0For hypre_newBoxLoop0For #define hypre_BoxLoop0End hypre_newBoxLoop0End #define hypre_BoxLoop1Begin hypre_newBoxLoop1Begin #define hypre_BoxLoop1For hypre_newBoxLoop1For #define hypre_BoxLoop1End hypre_newBoxLoop1End #define hypre_BoxLoop2Begin hypre_newBoxLoop2Begin #define hypre_BoxLoop2For hypre_newBoxLoop2For #define hypre_BoxLoop2End hypre_newBoxLoop2End #define hypre_BoxLoop3Begin hypre_newBoxLoop3Begin #define hypre_BoxLoop3For hypre_newBoxLoop3For #define hypre_BoxLoop3End hypre_newBoxLoop3End #define hypre_BoxLoop4Begin hypre_newBoxLoop4Begin #define hypre_BoxLoop4For hypre_newBoxLoop4For #define hypre_BoxLoop4End hypre_newBoxLoop4End #define hypre_BasicBoxLoop1Begin zypre_newBasicBoxLoop1Begin #define hypre_BasicBoxLoop2Begin zypre_newBasicBoxLoop2Begin /* Reduction BoxLoop1*/ #define hypre_BoxLoop1ReductionBegin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ reducesum) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ reducesum.nblocks = hypre_min( (hypre__tot+BLOCKSIZE-1)/BLOCKSIZE, 1024 ); \ ReductionBoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()), hypre__tot, \ HYPRE_LAMBDA (HYPRE_Int tid, HYPRE_Int nthreads, \ HYPRE_Int len) \ { \ for (HYPRE_Int idx = tid; \ idx < len; \ idx += nthreads) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); #define hypre_BoxLoop1ReductionEnd(i1, reducesum) \ } \ reducesum.BlockReduce(); \ }); \ hypre_fence(); \ } /* Reduction BoxLoop2 */ #define hypre_BoxLoop2ReductionBegin(ndim, loop_size, \ dbox1, start1, stride1, i1, \ dbox2, start2, stride2, i2, \ reducesum) \ { \ hypre_newBoxLoopInit(ndim,loop_size); \ hypre_BoxLoopDataDeclareK(1,ndim,loop_size,dbox1,start1,stride1); \ hypre_BoxLoopDataDeclareK(2,ndim,loop_size,dbox2,start2,stride2); \ reducesum.nblocks = hypre_min( (hypre__tot+BLOCKSIZE-1)/BLOCKSIZE, 1024 ); \ ReductionBoxLoopforall(hypre_HandleStructExecPolicy(hypre_handle()), hypre__tot, \ HYPRE_LAMBDA (HYPRE_Int tid, HYPRE_Int nthreads, \ HYPRE_Int len) \ { \ for (HYPRE_Int idx = tid; \ idx < len; \ idx += nthreads) \ { \ hypre_newBoxLoopDeclare(databox1); \ hypre_BoxLoopIncK(1,databox1,i1); \ hypre_BoxLoopIncK(2,databox2,i2); #define hypre_BoxLoop2ReductionEnd(i1, i2, reducesum) \ } \ reducesum.BlockReduce(); \ }); \ hypre_fence(); \ } #endif
ResultHandler.h
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* * Structures that collect search results from distance computations */ #pragma once #include <faiss/impl/AuxIndexStructures.h> #include <faiss/utils/Heap.h> #include <faiss/utils/partitioning.h> namespace faiss { /***************************************************************** * Heap based result handler *****************************************************************/ template <class C> struct HeapResultHandler { using T = typename C::T; using TI = typename C::TI; int nq; T* heap_dis_tab; TI* heap_ids_tab; int64_t k; // number of results to keep HeapResultHandler(size_t nq, T* heap_dis_tab, TI* heap_ids_tab, size_t k) : nq(nq), heap_dis_tab(heap_dis_tab), heap_ids_tab(heap_ids_tab), k(k) {} /****************************************************** * API for 1 result at a time (each SingleResultHandler is * called from 1 thread) */ struct SingleResultHandler { HeapResultHandler& hr; size_t k; T* heap_dis; TI* heap_ids; T thresh; SingleResultHandler(HeapResultHandler& hr) : hr(hr), k(hr.k) {} /// begin results for query # i void begin(size_t i) { heap_dis = hr.heap_dis_tab + i * k; heap_ids = hr.heap_ids_tab + i * k; heap_heapify<C>(k, heap_dis, heap_ids); thresh = heap_dis[0]; } /// add one result for query i void add_result(T dis, TI idx) { if (C::cmp(heap_dis[0], dis)) { heap_replace_top<C>(k, heap_dis, heap_ids, dis, idx); thresh = heap_dis[0]; } } /// series of results for query i is done void end() { heap_reorder<C>(k, heap_dis, heap_ids); } }; /****************************************************** * API for multiple results (called from 1 thread) */ size_t i0, i1; /// begin void begin_multiple(size_t i0, size_t i1) { this->i0 = i0; this->i1 = i1; for (size_t i = i0; i < i1; i++) { heap_heapify<C>(k, heap_dis_tab + i * k, heap_ids_tab + i * k); } } /// add results for query i0..i1 and j0..j1 void add_results(size_t j0, size_t j1, const T* dis_tab) { #pragma omp parallel for for (int64_t i = i0; i < i1; i++) { T* heap_dis = heap_dis_tab + i * k; TI* heap_ids = heap_ids_tab + i * k; const T* dis_tab_i = dis_tab + (j1 - j0) * (i - i0) - j0; T thresh = heap_dis[0]; for (size_t j = j0; j < j1; j++) { T dis = dis_tab_i[j]; if (C::cmp(thresh, dis)) { heap_replace_top<C>(k, heap_dis, heap_ids, dis, j); thresh = heap_dis[0]; } } } } /// series of results for queries i0..i1 is done void end_multiple() { // maybe parallel for for (size_t i = i0; i < i1; i++) { heap_reorder<C>(k, heap_dis_tab + i * k, heap_ids_tab + i * k); } } }; /***************************************************************** * Reservoir result handler * * A reservoir is a result array of size capacity > n (number of requested * results) all results below a threshold are stored in an arbitrary order. When * the capacity is reached, a new threshold is chosen by partitionning the * distance array. *****************************************************************/ /// Reservoir for a single query template <class C> struct ReservoirTopN { using T = typename C::T; using TI = typename C::TI; T* vals; TI* ids; size_t i; // number of stored elements size_t n; // number of requested elements size_t capacity; // size of storage T threshold; // current threshold ReservoirTopN() {} ReservoirTopN(size_t n, size_t capacity, T* vals, TI* ids) : vals(vals), ids(ids), i(0), n(n), capacity(capacity) { assert(n < capacity); threshold = C::neutral(); } void add(T val, TI id) { if (C::cmp(threshold, val)) { if (i == capacity) { shrink_fuzzy(); } vals[i] = val; ids[i] = id; i++; } } // reduce storage from capacity to anything // between n and (capacity + n) / 2 void shrink_fuzzy() { assert(i == capacity); threshold = partition_fuzzy<C>( vals, ids, capacity, n, (capacity + n) / 2, &i); } void to_result(T* heap_dis, TI* heap_ids) const { for (int j = 0; j < std::min(i, n); j++) { heap_push<C>(j + 1, heap_dis, heap_ids, vals[j], ids[j]); } if (i < n) { heap_reorder<C>(i, heap_dis, heap_ids); // add empty results heap_heapify<C>(n - i, heap_dis + i, heap_ids + i); } else { // add remaining elements heap_addn<C>(n, heap_dis, heap_ids, vals + n, ids + n, i - n); heap_reorder<C>(n, heap_dis, heap_ids); } } }; template <class C> struct ReservoirResultHandler { using T = typename C::T; using TI = typename C::TI; int nq; T* heap_dis_tab; TI* heap_ids_tab; int64_t k; // number of results to keep size_t capacity; // capacity of the reservoirs ReservoirResultHandler( size_t nq, T* heap_dis_tab, TI* heap_ids_tab, size_t k) : nq(nq), heap_dis_tab(heap_dis_tab), heap_ids_tab(heap_ids_tab), k(k) { // double then round up to multiple of 16 (for SIMD alignment) capacity = (2 * k + 15) & ~15; } /****************************************************** * API for 1 result at a time (each SingleResultHandler is * called from 1 thread) */ struct SingleResultHandler { ReservoirResultHandler& hr; std::vector<T> reservoir_dis; std::vector<TI> reservoir_ids; ReservoirTopN<C> res1; SingleResultHandler(ReservoirResultHandler& hr) : hr(hr), reservoir_dis(hr.capacity), reservoir_ids(hr.capacity) {} size_t i; /// begin results for query # i void begin(size_t i) { res1 = ReservoirTopN<C>( hr.k, hr.capacity, reservoir_dis.data(), reservoir_ids.data()); this->i = i; } /// add one result for query i void add_result(T dis, TI idx) { res1.add(dis, idx); } /// series of results for query i is done void end() { T* heap_dis = hr.heap_dis_tab + i * hr.k; TI* heap_ids = hr.heap_ids_tab + i * hr.k; res1.to_result(heap_dis, heap_ids); } }; /****************************************************** * API for multiple results (called from 1 thread) */ size_t i0, i1; std::vector<T> reservoir_dis; std::vector<TI> reservoir_ids; std::vector<ReservoirTopN<C>> reservoirs; /// begin void begin_multiple(size_t i0, size_t i1) { this->i0 = i0; this->i1 = i1; reservoir_dis.resize((i1 - i0) * capacity); reservoir_ids.resize((i1 - i0) * capacity); reservoirs.clear(); for (size_t i = i0; i < i1; i++) { reservoirs.emplace_back( k, capacity, reservoir_dis.data() + (i - i0) * capacity, reservoir_ids.data() + (i - i0) * capacity); } } /// add results for query i0..i1 and j0..j1 void add_results(size_t j0, size_t j1, const T* dis_tab) { // maybe parallel for #pragma omp parallel for for (int64_t i = i0; i < i1; i++) { ReservoirTopN<C>& reservoir = reservoirs[i - i0]; const T* dis_tab_i = dis_tab + (j1 - j0) * (i - i0) - j0; for (size_t j = j0; j < j1; j++) { T dis = dis_tab_i[j]; reservoir.add(dis, j); } } } /// series of results for queries i0..i1 is done void end_multiple() { // maybe parallel for for (size_t i = i0; i < i1; i++) { reservoirs[i - i0].to_result( heap_dis_tab + i * k, heap_ids_tab + i * k); } } }; /***************************************************************** * Result handler for range searches *****************************************************************/ template <class C> struct RangeSearchResultHandler { using T = typename C::T; using TI = typename C::TI; RangeSearchResult* res; float radius; RangeSearchResultHandler(RangeSearchResult* res, float radius) : res(res), radius(radius) {} /****************************************************** * API for 1 result at a time (each SingleResultHandler is * called from 1 thread) ******************************************************/ struct SingleResultHandler { // almost the same interface as RangeSearchResultHandler RangeSearchPartialResult pres; float radius; RangeQueryResult* qr = nullptr; SingleResultHandler(RangeSearchResultHandler& rh) : pres(rh.res), radius(rh.radius) {} /// begin results for query # i void begin(size_t i) { qr = &pres.new_result(i); } /// add one result for query i void add_result(T dis, TI idx) { if (C::cmp(radius, dis)) { qr->add(dis, idx); } } /// series of results for query i is done void end() {} ~SingleResultHandler() { pres.finalize(); } }; /****************************************************** * API for multiple results (called from 1 thread) ******************************************************/ size_t i0, i1; std::vector<RangeSearchPartialResult*> partial_results; std::vector<size_t> j0s; int pr = 0; /// begin void begin_multiple(size_t i0, size_t i1) { this->i0 = i0; this->i1 = i1; } /// add results for query i0..i1 and j0..j1 void add_results(size_t j0, size_t j1, const T* dis_tab) { RangeSearchPartialResult* pres; // there is one RangeSearchPartialResult structure per j0 // (= block of columns of the large distance matrix) // it is a bit tricky to find the poper PartialResult structure // because the inner loop is on db not on queries. if (pr < j0s.size() && j0 == j0s[pr]) { pres = partial_results[pr]; pr++; } else if (j0 == 0 && j0s.size() > 0) { pr = 0; pres = partial_results[pr]; pr++; } else { // did not find this j0 pres = new RangeSearchPartialResult(res); partial_results.push_back(pres); j0s.push_back(j0); pr = partial_results.size(); } for (size_t i = i0; i < i1; i++) { const float* ip_line = dis_tab + (i - i0) * (j1 - j0); RangeQueryResult& qres = pres->new_result(i); for (size_t j = j0; j < j1; j++) { float dis = *ip_line++; if (C::cmp(radius, dis)) { qres.add(dis, j); } } } } void end_multiple() {} ~RangeSearchResultHandler() { if (partial_results.size() > 0) { RangeSearchPartialResult::merge(partial_results); } } }; } // namespace faiss
GraphTango.h
#pragma once #include <cstdint> #include <stack> #include <vector> #include <variant> #include <cstring> #include <algorithm> #include <omp.h> #include <string> #include <iostream> #include <atomic> #include <unordered_map> #include <queue> #include <cassert> #include <immintrin.h> #include <fstream> #include <map> #include <bitset> #include "omp.h" #include "abstract_data_struc.h" #include "types.h" #include "LockFreePoolWithList.h" #include "CustomAllocator.h" #include "VertexArray.h" #include "GEmpty.h" #include "common.h" #include "global.h" using namespace std; template<typename Neigh> class GraphTango : public dataStruc { public: void print(void) override { #ifdef CALC_MEM_PER_EDGE cout << "Total memory req: " << globalAllocator.totMem << endl; #endif // std::cout << "Inserts--------------------" << std::endl; // std::cout << " Total: " << insTot << std::endl; // std::cout << " Succ : " << insSucc << std::endl; // std::cout << " Fail : " << insTot - insSucc << std::endl; // std::cout << std::endl; // // std::cout << "Deletes--------------------" << std::endl; // std::cout << " Total: " << delTot << std::endl; // std::cout << " Succ : " << delSucc << std::endl; // std::cout << " Fail : " << delTot - delSucc << std::endl; // std::cout << std::endl; // // std::cout << "Final number of edges: " << insSucc - delSucc << std::endl; // ofstream out("probing_dist.csv"); // for(auto it : probingDist){ // out << it.first << "," << it.second << endl; // } } #ifdef USE_HYBRID_HASHMAP VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray.resize(numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray.outDegree[i] = 0; vArray.outCapacity[i] = 0; vArray.outNeighArr[i] = nullptr; vArray.outMapArr[i] = nullptr; vArray.inDegree[i] = 0; vArray.inCapacity[i] = 0; vArray.inNeighArr[i] = nullptr; vArray.inMapArr[i] = nullptr; } cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray.inDegree[n]; } int64_t out_degree(NodeID n) override { return vArray.outDegree[n]; } void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, graphite_hashmap* __restrict &locMap, const Idx dstId, const Weight weight, u64& edgeCnt){ //insTot++; if(deg == cap){ const u64 newCap = getNextPow2MinRet(cap * 2); Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); cap = newCap; neighs = newPtr; if(deg > 0){ memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){ //switch from linear to hashed mode locMap = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap)); new (locMap) graphite_hashmap(); //add existing nodes to hash const Neigh* __restrict neighs = newPtr; for(u64 i = 0; i < deg; i++){ (*locMap)[neighs[i].node] = i; } } } //search for existing edge if(!locMap){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < deg; i++){ if(neighs[i].node == dstId){ nn = neighs + i; break; } } if(!nn){ //edge not found, insert neighs[deg].node = dstId; neighs[deg].setWeight(weight); deg++; edgeCnt++; //insSucc++; } else{ //edge found, update nn->setWeight(weight); } } else { //using hashed mode const auto& it = locMap->find(dstId); if(it == locMap->end()){ //edge not found, insert Neigh& nn = neighs[deg]; nn.node = dstId; nn.setWeight(weight); (*locMap)[dstId] = deg; deg++; edgeCnt++; //insSucc++; } else{ //edge found, update weight neighs[it->second].setWeight(weight); } } } void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, graphite_hashmap* __restrict &locMap, const Idx dstId, u64& edgeCnt){ //delTot++; //search for existing edge if(!locMap){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < deg; i++){ if(neighs[i].node == dstId){ nn = neighs + i; break; } } if(!nn){ //edge not found, nothing to do return; } else{ //edge found, delete deg--; edgeCnt--; //delSucc++; //move last elem *nn = neighs[deg]; } } else { //using hashed mode const auto& it = locMap->find(dstId); if(it == locMap->end()){ //edge not found, nothing to do return; } else{ //edge found, delete deg--; edgeCnt--; //delSucc++; const u64 loc = it->second; locMap->erase(it); if(__builtin_expect(loc != deg, false)){ //not the last element... move neighs[loc] = neighs[deg]; (*locMap)[neighs[loc].node] = loc; } } } if((cap > 4) && ((deg * 4) <= cap)){ const u64 newCap = cap / 2; Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); cap = newCap; neighs = newPtr; memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap * 2 * sizeof(Neigh)); if(__builtin_expect(newCap < HYBRID_HASH_PARTITION, 0)){ //switch from hashed to linear mode globalAllocator.freePow2(locMap, sizeof(graphite_hashmap)); locMap = nullptr; } } } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[actualTh].edgeCnt); } } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage); } else{ //delete in edge deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage); } } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage); } else{ //delete out edge deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[0].edgeCnt); //delete in edge deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_HYBRID_HASHMAP_WITH_CFH #define FLAG_EMPTY_SLOT 0xFFFFFFFFU #define FLAG_TOMB_STONE 0xFFFFFFFEU VertexArray<Neigh> vArray; const int num_threads; //map<u64, u64> probingDist; //u64 probe; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray.resize(numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray.outDegree[i] = 0; vArray.outCapacity[i] = 0; vArray.outNeighArr[i] = nullptr; vArray.outMapArr[i] = nullptr; vArray.inDegree[i] = 0; vArray.inCapacity[i] = 0; vArray.inNeighArr[i] = nullptr; vArray.inMapArr[i] = nullptr; } //vArray.usingHash.resize(numNodes, false); //vArray.dstLocMap.resize(numNodes); cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; cout << "Num threads: " << omp_get_num_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray.inDegree[n]; } int64_t out_degree(NodeID n) override { return vArray.outDegree[n]; } //for now, use linear probing inline DstLocPair* findInsertionPoint(DstLocPair* __restrict &locMap, u32 dst, u32 tableSize){ u32 idx = dst & (tableSize - 1); while(true){ if((locMap[idx].dst == dst) || (locMap[idx].dst == FLAG_EMPTY_SLOT)){ //found key or an empty slot return locMap + idx; } //move on idx++; if(idx == tableSize){ idx = 0; } } return nullptr; } void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, DstLocPair* __restrict &locMap, const Idx dstId, const Weight weight, u64& edgeCnt){ //insTot++; if(deg == cap){ const u64 newCap = getNextPow2MinRet(cap * 2); Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); cap = newCap; neighs = newPtr; if(deg > 0){ memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } if(newCap >= HYBRID_HASH_PARTITION){ if(locMap){ //free old loc map globalAllocator.freePow2(locMap, cap * sizeof(DstLocPair)); } locMap = (DstLocPair*)globalAllocator.allocate(sizeof(DstLocPair) * cap * 2); memset(locMap, -1, sizeof(DstLocPair) * cap * 2); const u32 mask = cap * 2 - 1; //add existing nodes to hash const Neigh* __restrict nn = neighs; for(u64 i = 0; i < deg; i++){ const u32 dst = nn[i].node; u32 idx = dst & mask; while(true){ if(locMap[idx].dst == FLAG_EMPTY_SLOT){ //found insertion point locMap[idx].dst = dst; locMap[idx].loc = i; break; } //move on idx++; if(idx == (cap * 2)){ idx = 0; } } } } } //search for existing edge if(!locMap){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < deg; i++){ if(neighs[i].node == dstId){ nn = neighs + i; break; } } if(!nn){ //edge not found, insert neighs[deg].node = dstId; neighs[deg].setWeight(weight); deg++; edgeCnt++; //insSucc++; } else{ //edge found, update nn->setWeight(weight); } } else { //using hashed mode u32 idx = dstId & (cap * 2 - 1); //probe = 0; while(true){ //probe++; if(locMap[idx].dst == FLAG_EMPTY_SLOT){ //edge not found, insert Neigh& nn = neighs[deg]; nn.node = dstId; nn.setWeight(weight); locMap[idx].dst = dstId; locMap[idx].loc = deg; deg++; edgeCnt++; //insSucc++; //probingDist[probe]++; return; } else if(locMap[idx].dst == dstId){ //edge found, update weight neighs[locMap[idx].loc].setWeight(weight); //probingDist[probe]++; return; } //move on idx++; if(idx == (cap * 2)){ idx = 0; } } } } void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, DstLocPair* __restrict &locMap, const Idx dstId, u64& edgeCnt){ //delTot++; //search for existing edge if(!locMap){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < deg; i++){ if(neighs[i].node == dstId){ nn = neighs + i; break; } } if(!nn){ //edge not found, return return; } else{ //edge found, delete deg--; edgeCnt--; //delSucc++; nn->node = neighs[deg].node; nn->setWeight(neighs[deg].getWeight()); } } else { //using hashed mode u32 idx = dstId & (cap * 2 - 1); while(true){ if(locMap[idx].dst == FLAG_EMPTY_SLOT){ //edge not found, return return; } else if(locMap[idx].dst == dstId){ //edge found, delete deg--; edgeCnt--; //delSucc++; locMap[idx].dst = FLAG_TOMB_STONE; //invalidate previous hash-table entry const u32 loc = locMap[idx].loc; if(__builtin_expect(loc != deg, true)){ //nothing to do if last entry is removed const u32 node = neighs[deg].node; //copy last entry neighs[loc] = neighs[deg]; //point to correct location of the swapped entry u32 idxMoved = node & (cap * 2 - 1); while(locMap[idxMoved].dst != node){ idxMoved++; if(idxMoved == (cap * 2)){ idxMoved = 0; } } locMap[idxMoved].loc = loc; } break; } //move on idx++; if(idx == (cap * 2)){ idx = 0; } } } if((cap > 4) && (deg * 4) <= cap){ //time to reduce capacity const u64 newCap = cap / 2; Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); //copy old adjList and free memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, cap * sizeof(Neigh)); cap = newCap; neighs = newPtr; if(locMap){ //free old loc map (if any) globalAllocator.freePow2(locMap, cap * sizeof(DstLocPair)); locMap = nullptr; } if(cap >= HYBRID_HASH_PARTITION){ locMap = (DstLocPair*)globalAllocator.allocate(sizeof(DstLocPair) * cap * 2); memset(locMap, -1, sizeof(DstLocPair) * cap * 2); //This is bad. Is there any way to circumvent this? const u32 mask = cap * 2 - 1; //add existing nodes to hash const Neigh* __restrict nn = neighs; for(u64 i = 0; i < deg; i++){ const u32 dst = nn[i].node; u32 idx = dst & mask; while(true){ if(locMap[idx].dst == FLAG_EMPTY_SLOT){ //found insertion point locMap[idx].dst = dst; locMap[idx].loc = i; break; } //move on idx++; if(idx == (cap * 2)){ idx = 0; } } } } } } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[0].edgeCnt); } } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage); } else{ //delete in edge deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage); } } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage); } else{ //delete out edge deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[0].edgeCnt); //delete in edge deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #if defined(USE_GT_BALANCED) Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; #ifdef CALC_TYPE_SWITCH typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u64 switchCnt = 0; u8 pad[40]; } ThreadInfo; #else typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; #endif alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0; } cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ #ifdef CALC_TYPE_SWITCH u32 switchCnt = 0; for(u64 i = 0; i < num_threads; i++){ switchCnt += thInfo[i].switchCnt; } cout << "Switch Count: " << switchCnt << endl; #endif } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel { const i64 actualTh = omp_get_thread_num(); LIKWID_MARKER_START("upd"); for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } #ifdef CALC_TYPE_SWITCH VType initType = VType::VTYPE_3; if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH0){ initType = VType::VTYPE_1; } else if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH1){ initType = VType::VTYPE_2; } #endif if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt); } #ifdef CALC_TYPE_SWITCH VType finType = VType::VTYPE_3; if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH0){ finType = VType::VTYPE_1; } else if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH1){ finType = VType::VTYPE_2; } if(initType != finType){ thInfo[actualTh].switchCnt++; } #endif } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } #ifdef CALC_TYPE_SWITCH VType initType = VType::VTYPE_3; if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH0){ initType = VType::VTYPE_1; } else if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH1){ initType = VType::VTYPE_2; } #endif u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } #ifdef CALC_TYPE_SWITCH VType finType = VType::VTYPE_3; if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH0){ finType = VType::VTYPE_1; } else if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH1){ finType = VType::VTYPE_2; } if(initType != finType){ thInfo[actualTh].switchCnt++; } #endif } } LIKWID_MARKER_STOP("upd"); } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; #ifdef CALC_TYPE_SWITCH switchCnt += thInfo[i].switchCnt; thInfo[i].switchCnt = 0; #endif } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_GT_BALANCED_TYPE3_ONLY Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = 0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = 0; } //cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; //cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel { const i64 actualTh = omp_get_thread_num(); LIKWID_MARKER_START("upd"); for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt); } } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } } LIKWID_MARKER_STOP("upd"); } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_GT_BALANCED_DYN_PARTITION Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u32 nodeCnt = 0; u32 inCurrEdge = 0; u32 inNewEdge = 0; u32 inStart = 0; u32 inEnd = 0; u32 outCurrEdge = 0; u32 outNewEdge = 0; u32 outStart = 0; u32 outEnd = 0; u8 pad[28]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0; } cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif memset(thInfo, 0, sizeof(ThreadInfo) * 32); const u32 avgNodePerTh = numNodes / numThreads; thInfo[0].inStart = 0; thInfo[0].outStart = 0; for(u32 i = 0; i < numThreads-1; i++){ thInfo[i].inEnd = thInfo[i].inStart + avgNodePerTh; thInfo[i+1].inStart = thInfo[i].inEnd + 1; thInfo[i].outEnd = thInfo[i].outStart + avgNodePerTh; thInfo[i+1].outStart = thInfo[i].outEnd + 1; } thInfo[numThreads - 1].inEnd = numNodes; thInfo[numThreads - 1].outEnd = numNodes; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel { ThreadInfo& th = thInfo[omp_get_thread_num()]; const u32 inStart = th.inStart; const u32 inEnd = th.inEnd; const u32 outStart = th.outStart; const u32 outEnd = th.outEnd; LIKWID_MARKER_START("upd"); for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; //i64 targetTh = (src / 64) & thMask; //i64 targetTh = (src / 64) % num_threads; if(src >= outStart && src <= outEnd){ if(!el[i].sourceExists){ th.nodeCnt++; } if(!el[i].destExists){ th.nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, th.outNewEdge); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, th.outNewEdge); } } //targetTh = (dst / 64) & thMask; //targetTh = (dst / 64) % num_threads; if(dst >= inStart && dst <= inEnd){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, th.inNewEdge); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, th.inNewEdge); } } } LIKWID_MARKER_STOP("upd"); } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].inNewEdge + thInfo[i].outNewEdge; thInfo[i].inCurrEdge += thInfo[i].inNewEdge; thInfo[i].outCurrEdge += thInfo[i].outNewEdge; thInfo[i].inNewEdge = 0; thInfo[i].outNewEdge = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } float avgEdge = (num_edges / 2.0) / num_nodes; i64 inBalance = 0; i64 outBalance = 0; for(u64 i = 0; i < (num_threads - 1); i++){ ThreadInfo& th = thInfo[i]; //balance in edges if(th.inCurrEdge > avgEdge){ //decrease workload while(th.inCurrEdge > avgEdge){ const u32 remEdge = vArray[th.inEnd].inEdges.degree; inBalance += remEdge; th.inEnd--; th.inCurrEdge -= remEdge; } } else{ //increase workload while(th.inCurrEdge < avgEdge){ th.inEnd++; const u32 remEdge = vArray[th.inEnd].inEdges.degree; inBalance -= remEdge; th.inCurrEdge += remEdge; } } thInfo[i+1].inStart = th.inEnd + 1; thInfo[i+1].inCurrEdge += inBalance; //balance out edges if(th.outCurrEdge > avgEdge){ //decrease workload while(th.outCurrEdge > avgEdge){ const u32 remEdge = vArray[th.outEnd].outEdges.degree; outBalance += remEdge; th.outEnd--; th.outCurrEdge -= remEdge; } } else{ //increase workload while(th.outCurrEdge < avgEdge){ th.outEnd++; const u32 remEdge = vArray[th.outEnd].outEdges.degree; outBalance -= remEdge; th.outCurrEdge += remEdge; } } thInfo[i+1].outStart = th.outEnd + 1; thInfo[i+1].outCurrEdge += outBalance; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_GT_BALANCED_STDMAP Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0; } cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel { LIKWID_MARKER_START("upd"); for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt); } } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } } LIKWID_MARKER_STOP("upd"); } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #if defined(USE_GT_BALANCED_MALLOC_STDMAP) || defined(USE_GT_BALANCED_ABSEIL) || defined(USE_GT_BALANCED_RHH) || defined(USE_GT_BALANCED_TSL_RHH) Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0; } cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel { LIKWID_MARKER_START("upd"); for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt); } } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } } LIKWID_MARKER_STOP("upd"); } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_GT_BALANCED_MALLOC Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0; } cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel { LIKWID_MARKER_START("upd"); for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt); } } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } } LIKWID_MARKER_STOP("upd"); } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_GT_UPDATE Vertex<Neigh>* vArray; //VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0; } cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl; cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl; cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl; #ifdef _OPENMP cout << "Max threads: " << omp_get_max_threads() << endl; #endif property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } // void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, DstLocPair* __restrict &locMap, const Idx dstId, u64& edgeCnt){ // //delTot++; // //search for existing edge // if(!locMap){ // //using linear mode // Neigh* __restrict nn = nullptr; // for(u64 i = 0; i < deg; i++){ // if(neighs[i].node == dstId){ // nn = neighs + i; // break; // } // } // if(!nn){ // //edge not found, return // return; // } // else{ // //edge found, delete // deg--; // edgeCnt--; // //delSucc++; // nn->node = neighs[deg].node; // nn->setWeight(neighs[deg].getWeight()); // } // } // else { // //using hashed mode // u32 idx = dstId & (cap * 2 - 1); // while(true){ // if(locMap[idx].dst == FLAG_EMPTY_SLOT){ // //edge not found, return // return; // } // else if(locMap[idx].dst == dstId){ // //edge found, delete // deg--; // edgeCnt--; // //delSucc++; // locMap[idx].dst = FLAG_TOMB_STONE; //invalidate previous hash-table entry // // const u32 loc = locMap[idx].loc; // if(__builtin_expect(loc != deg, true)){ //nothing to do if last entry is removed // const u32 node = neighs[deg].node; // //copy last entry // neighs[loc] = neighs[deg]; // // //point to correct location of the swapped entry // u32 idxMoved = node & (cap * 2 - 1); // while(locMap[idxMoved].dst != node){ // idxMoved++; // if(idxMoved == (cap * 2)){ // idxMoved = 0; // } // } // locMap[idxMoved].loc = loc; // } // break; // } // //move on // idx++; // if(idx == (cap * 2)){ // idx = 0; // } // } // } // // if((cap > 4) && (deg * 4) <= cap){ // //time to reduce capacity // // const u64 newCap = cap / 2; // Neigh* __restrict oldPtr = neighs; // Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); // // //copy old adjList and free // memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); // globalAllocator.freePow2(oldPtr, cap * sizeof(Neigh)); // // cap = newCap; // neighs = newPtr; // // if(locMap){ // //free old loc map (if any) // globalAllocator.freePow2(locMap, cap * sizeof(DstLocPair)); // locMap = nullptr; // } // // if(cap >= HYBRID_HASH_PARTITION){ // locMap = (DstLocPair*)globalAllocator.allocate(sizeof(DstLocPair) * cap * 2); // memset(locMap, -1, sizeof(DstLocPair) * cap * 2); //This is bad. Is there any way to circumvent this? // // const u32 mask = cap * 2 - 1; // // //add existing nodes to hash // const Neigh* __restrict nn = neighs; // for(u64 i = 0; i < deg; i++){ // const u32 dst = nn[i].node; // u32 idx = dst & mask; // while(true){ // if(locMap[idx].dst == FLAG_EMPTY_SLOT){ // //found insertion point // locMap[idx].dst = dst; // locMap[idx].loc = i; // break; // } // //move on // idx++; // if(idx == (cap * 2)){ // idx = 0; // } // } // } // } // } // } void update(const EdgeList& el) override { //probe = 0; const u64 batchSize = el.size(); #ifdef _OPENMP //int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); //i64 targetTh = (src / 64) & thMask; i64 targetTh = (src / 64) % num_threads; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt); } } //targetTh = (dst / 64) & thMask; targetTh = (dst / 64) % num_threads; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insertion //insert out edge vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage); } else{ //delete out edge vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.deleteEdge(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_HYBRID_HASHMAP_WITH_GROUPING Vertex<Neigh>* vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>)); memset(vArray, 0, numNodes * sizeof(Vertex<Neigh>)); cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl; cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ free(vArray); } void print() override { cout << "Done" << endl; } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){ if(edgePtr->degree == edgePtr->capacity){ const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2); Neigh* __restrict oldPtr = edgePtr->neighArr; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); edgePtr->capacity = newCap; edgePtr->neighArr = newPtr; if(edgePtr->degree > 0){ memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){ //switch from linear to hashed mode edgePtr->mapArr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap)); new (edgePtr->mapArr) graphite_hashmap(); //add existing nodes to hash const Neigh* __restrict neighs = newPtr; for(u64 i = 0; i < edgePtr->degree; i++){ (*edgePtr->mapArr)[neighs[i].node] = i; } } } //search for existing edge if(!edgePtr->mapArr){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < edgePtr->degree; i++){ if(edgePtr->neighArr[i].node == dstId){ nn = edgePtr->neighArr + i; break; } } if(!nn){ //edge not found, insert edgePtr->neighArr[edgePtr->degree].node = dstId; edgePtr->neighArr[edgePtr->degree].setWeight(weight); edgePtr->degree++; edgeCnt++; } else{ //edge found, update nn->setWeight(weight); } } else { //using hashed mode const auto& it = edgePtr->mapArr->find(dstId); if(it == edgePtr->mapArr->end()){ //edge not found, insert Neigh& nn = edgePtr->neighArr[edgePtr->degree]; nn.node = dstId; nn.setWeight(weight); (*edgePtr->mapArr)[dstId] = edgePtr->degree; edgePtr->degree++; edgeCnt++; } else{ //edge found, update weight edgePtr->neighArr[it->second].setWeight(weight); } } } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } //insert out edge insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt); } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } //insert in edge insertEdge(&vArray[dst].inEdges, src, el[i].weight, thInfo[actualTh].edgeCnt); } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } //insert out edge insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge u64 garbage; insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage); } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_SORTED_EDGES Vertex<Neigh>* vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>)); memset(vArray, 0, numNodes * sizeof(Vertex<Neigh>)); cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl; cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ free(vArray); } void print() override { cout << "Done" << endl; } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){ Neigh* __restrict insLoc = nullptr; //first, do linear search for(u64 i = 0; i < edgePtr->degree; i++){ if(edgePtr->neighArr[i].node == dstId){ //found insLoc = edgePtr->neighArr + i; break; } } if(!insLoc && edgePtr->degree > LINEAR_BUFF_SIZE){ //do binary search u64 low = LINEAR_BUFF_SIZE; u64 high = edgePtr->degree; } if(!insLoc){ //not found, insert if(edgePtr->degree == edgePtr->capacity){ const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2); Neigh* __restrict oldPtr = edgePtr->neighArr; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); edgePtr->capacity = newCap; edgePtr->neighArr = newPtr; if(edgePtr->degree > 0){ memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } } insLoc->node = dstId; edgePtr->degree++; edgeCnt++; } insLoc->setWeight(weight); } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } //insert out edge insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt); } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } //insert in edge u64 garbase; insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbase); } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } //insert out edge insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge u64 garbage; insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage); } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_HYBRID_HASHMAP_WITH_GROUPING_TIGHTER Vertex<Neigh>* vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>)); for(u64 i = 0; i < numNodes; i++){ Vertex<Neigh>& v = vArray[i]; v.inEdges.degree = 0; v.inEdges.capacity = INITIAL_EDGES; v.inEdges.neighArr = v.inEdges.neigh; v.inEdges.mapArr = nullptr; v.outEdges.degree = 0; v.outEdges.capacity = INITIAL_EDGES; v.outEdges.neighArr = v.outEdges.neigh; v.outEdges.mapArr = nullptr; } cout << "Size of EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl; cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl; cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Size of Neigh: " << sizeof(Neigh) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ free(vArray); } void print() override { cout << "Done" << endl; } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){ if(edgePtr->degree == edgePtr->capacity){ const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2); Neigh* __restrict oldPtr = edgePtr->neighArr; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); edgePtr->capacity = newCap; edgePtr->neighArr = newPtr; if(edgePtr->degree > 0){ memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh)); if(oldPtr != edgePtr->neigh){ globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } } if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){ //switch from linear to hashed mode edgePtr->mapArr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap)); new (edgePtr->mapArr) graphite_hashmap(); //add existing nodes to hash const Neigh* __restrict neighs = newPtr; for(u64 i = 0; i < edgePtr->degree; i++){ (*edgePtr->mapArr)[neighs[i].node] = i; } } } //search for existing edge if(!edgePtr->mapArr){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < edgePtr->degree; i++){ if(edgePtr->neighArr[i].node == dstId){ nn = edgePtr->neighArr + i; break; } } if(!nn){ //edge not found, insert edgePtr->neighArr[edgePtr->degree].node = dstId; edgePtr->neighArr[edgePtr->degree].setWeight(weight); edgePtr->degree++; edgeCnt++; } else{ //edge found, update nn->setWeight(weight); } } else { //using hashed mode const auto& it = edgePtr->mapArr->find(dstId); if(it == edgePtr->mapArr->end()){ //edge not found, insert Neigh& nn = edgePtr->neighArr[edgePtr->degree]; nn.node = dstId; nn.setWeight(weight); (*edgePtr->mapArr)[dstId] = edgePtr->degree; edgePtr->degree++; edgeCnt++; } else{ //edge found, update weight edgePtr->neighArr[it->second].setWeight(weight); } } } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } //insert out edge insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt); } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } //insert in edge u64 garbase; insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbase); } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } //insert out edge insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge u64 garbage; insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage); } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_HYBRID_HASHMAP_WITH_GROUPING_AND_EDGE_ARR_LOCKING Vertex<Neigh>* vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>)); //memset(vArray, 0, numNodes * sizeof(Vertex<Neigh>)); for(u64 i = 0; i < numNodes; i++){ vArray[i].inEdges.degree = 0; vArray[i].inEdges.capacity = 0; vArray[i].inEdges.neighArr = nullptr; vArray[i].inEdges.mapArr = nullptr; vArray[i].outEdges.degree = 0; vArray[i].outEdges.capacity = 0; vArray[i].outEdges.neighArr = nullptr; vArray[i].outEdges.mapArr = nullptr; #ifdef _OPENMP omp_init_lock(&vArray[i].inEdges.lock); omp_init_lock(&vArray[i].outEdges.lock); #endif } cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl; cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ free(vArray); } void print() override { cout << "Done" << endl; } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){ if(edgePtr->degree == edgePtr->capacity){ const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2); Neigh* __restrict oldPtr = edgePtr->neighArr; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); edgePtr->capacity = newCap; edgePtr->neighArr = newPtr; if(edgePtr->degree > 0){ memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){ //switch from linear to hashed mode edgePtr->mapArr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap)); new (edgePtr->mapArr) graphite_hashmap(); //add existing nodes to hash const Neigh* __restrict neighs = newPtr; for(u64 i = 0; i < edgePtr->degree; i++){ (*edgePtr->mapArr)[neighs[i].node] = i; } } } //search for existing edge if(!edgePtr->mapArr){ //using linear mode Neigh* __restrict nn = nullptr; for(u64 i = 0; i < edgePtr->degree; i++){ if(edgePtr->neighArr[i].node == dstId){ nn = edgePtr->neighArr + i; break; } } if(!nn){ //edge not found, insert edgePtr->neighArr[edgePtr->degree].node = dstId; edgePtr->neighArr[edgePtr->degree].setWeight(weight); edgePtr->degree++; edgeCnt++; } else{ //edge found, update nn->setWeight(weight); } } else { //using hashed mode const auto& it = edgePtr->mapArr->find(dstId); if(it == edgePtr->mapArr->end()){ //edge not found, insert Neigh& nn = edgePtr->neighArr[edgePtr->degree]; nn.node = dstId; nn.setWeight(weight); (*edgePtr->mapArr)[dstId] = edgePtr->degree; edgePtr->degree++; edgeCnt++; } else{ //edge found, update weight edgePtr->neighArr[it->second].setWeight(weight); } } } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #pragma omp parallel for for(u64 i = 0; i < batchSize; i++){ const Edge e = el[i]; const int th = omp_get_thread_num(); if(!e.sourceExists){ thInfo[th].nodeCnt++; } if(!e.destExists){ thInfo[th].nodeCnt++; } if(!affected[e.source]){ affected[e.source] = true; } if(!affected[e.destination]){ affected[e.destination] = true; } //take a lock on the out edge of src omp_set_lock(&vArray[e.source].outEdges.lock); //insert outgoing edge insertEdge(&vArray[e.source].outEdges, e.destination, e.weight, thInfo[th].edgeCnt); //release lock omp_unset_lock(&vArray[e.source].outEdges.lock); //take a lock on the incoming edge of dest omp_set_lock(&vArray[e.destination].inEdges.lock); //insert incoming edge u64 garbage; insertEdge(&vArray[e.destination].inEdges, e.source, e.weight, garbage); //release lock omp_unset_lock(&vArray[e.destination].inEdges.lock); } //#ifdef _OPENMP // int thMask = (1 << getNextPow2Log2(num_threads)) - 1; // // #pragma omp parallel // for(u64 i = 0; i < batchSize; i++){ // const i64 src = el[i].source; // const i64 dst = el[i].destination; // const i64 actualTh = omp_get_thread_num(); // // i64 targetTh = (src / 64) & thMask; // if(targetTh == actualTh){ // if(!el[i].sourceExists){ // thInfo[actualTh].nodeCnt++; // } // if(!el[i].destExists){ // thInfo[actualTh].nodeCnt++; // } // // if(!affected[src]){ // affected[src] = true; // } // // //insert out edge // insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt); // } // // targetTh = (dst / 64) & thMask; // if(targetTh == actualTh){ // if(!affected[dst]){ // affected[dst] = true; // } // //insert in edge // u64 garbase; // insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbase); // } // // } //#else // for(u64 i = 0; i < batchSize; i++){ // const u64 src = el[i].source; // const u64 dst = el[i].destination; // // if(!el[i].sourceExists){ // thInfo[0].nodeCnt++; // } // if(!el[i].destExists){ // thInfo[0].nodeCnt++; // } // if(!affected[src]){ // affected[src] = true; // } // if(!affected[dst]){ // affected[dst] = true; // } // // //insert out edge // insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt); // // //insert in edge // u64 garbage; // insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage); // } //#endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_ONLY_HASHMAP VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray.resize(numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray.outDegree[i] = 0; vArray.outCapacity[i] = 0; vArray.outNeighArr[i] = nullptr; vArray.inDegree[i] = 0; vArray.inCapacity[i] = 0; vArray.inNeighArr[i] = nullptr; } //vArray.usingHash.resize(numNodes, false); //vArray.dstLocMap.resize(numNodes); cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } void print() override { cout << "Done" << endl; } int64_t in_degree(NodeID n) override { return vArray.inDegree[n]; } int64_t out_degree(NodeID n) override { return vArray.outDegree[n]; } void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, graphite_hashmap __restrict &locMap, const Idx dstId, const Weight weight, u64& edgeCnt){ if(deg == cap){ const u64 newCap = getNextPow2MinRet(cap * 2); Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); cap = newCap; neighs = newPtr; if(deg > 0){ memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } } //using hashed mode const auto& it = locMap.find(dstId); if(it == locMap.end()){ //edge not found, insert Neigh& nn = neighs[deg]; nn.node = dstId; nn.setWeight(weight); locMap[dstId] = deg; deg++; edgeCnt++; } else{ //edge found, update weight neighs[it->second].setWeight(weight); } } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt); } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } //insert in edge u64 garbase; insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbase); } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge u64 garbage; insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage); } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } // void insertEdge(Idx srcId, Idx dstId, Weight weight, int thId){ // const u64 deg = vArray.outDegree[srcId]; // // if(__builtin_expect(deg == vArray.outCapacity[srcId], 0)){ // const u64 newCap = getNextPow2(vArray.outCapacity[srcId] * 2); // // // Neigh* __restrict oldPtr = vArray.outNeighArr[srcId]; // Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); // // vArray.outCapacity[srcId] = newCap; // vArray.outNeighArr[srcId] = newPtr; // // if(deg > 0){ // memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); // globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); // } // // if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){ // //switch from linear to hashed mode // graphite_hashmap* __restrict hashPtr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap)); // new (hashPtr) graphite_hashmap(); // // vArray.outMapArr[srcId] = hashPtr; // // //add existing nodes to hash // const Neigh* __restrict neighs = newPtr; // for(u64 i = 0; i < deg; i++){ // (*hashPtr)[neighs[i].node] = i; // } // } // } // // //search for existing edge // graphite_hashmap* __restrict locMap = vArray.outMapArr[srcId]; // Neigh* __restrict neigh = vArray.outNeighArr[srcId]; // // if(!locMap){ // //using linear mode // Neigh* __restrict nn = nullptr; // for(u64 i = 0; i < deg; i++){ // if(neigh[i].node == dstId){ // nn = neigh + i; // break; // } // } // if(!nn){ // //edge not found, insert // neigh[deg].node = dstId; // neigh[deg].setWeight(weight); // vArray.outDegree[srcId]++; // // thInfo[thId].edgeCnt++; // } // else{ // //edge found, update // nn->setWeight(weight); // } // } // else { // //using hashed mode // const auto& it = locMap->find(dstId); // if(it == locMap->end()){ // //edge not found, insert // Neigh& nn = neigh[deg]; // nn.node = dstId; // nn.setWeight(weight); // (*locMap)[dstId] = deg; // vArray.outDegree[srcId]++; // // thInfo[thId].edgeCnt++; // } // else{ // //edge found, update weight // neigh[it->second].setWeight(weight); // } // } // // //we do not need atomic operation on affected as long as "some" thread updates it // if(!affected[srcId]){ // affected[srcId] = true; // } // if(!affected[dstId]){ // affected[dstId] = true; // } // } #endif #ifdef USE_ONLY_LINEAR VertexArray<Neigh> vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray.resize(numNodes); #pragma omp parallel for for(u64 i = 0; i < numNodes; i++){ vArray.outDegree[i] = 0; vArray.outCapacity[i] = 0; vArray.outNeighArr[i] = nullptr; vArray.inDegree[i] = 0; vArray.inCapacity[i] = 0; vArray.inNeighArr[i] = nullptr; } cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ } int64_t in_degree(NodeID n) override { return vArray.inDegree[n]; } int64_t out_degree(NodeID n) override { return vArray.outDegree[n]; } void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, const Idx dstId, const Weight weight, u64& edgeCnt){ insTot++; if(deg == cap){ const u64 newCap = getNextPow2MinRet(cap * 2); Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); cap = newCap; neighs = newPtr; if(deg > 0){ memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh)); } } //search for existing edge Neigh* __restrict nn = nullptr; for(u64 i = 0; i < deg; i++){ if(neighs[i].node == dstId){ nn = neighs + i; break; } } if(!nn){ //edge not found, insert neighs[deg].node = dstId; neighs[deg].setWeight(weight); deg++; edgeCnt++; insSucc++; } else{ //edge found, update nn->setWeight(weight); } } void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, const Idx dstId, u64& edgeCnt){ delTot++; //search for existing edge Neigh* __restrict nn = nullptr; for(u64 i = 0; i < deg; i++){ if(neighs[i].node == dstId){ nn = neighs + i; break; } } if(!nn){ //edge not found, return return; } else{ //edge found, delete deg--; edgeCnt--; delSucc++; *nn = neighs[deg]; } if((cap > 4) && (deg * 4) <= cap){ //reduce size const u64 newCap = cap / 2; Neigh* __restrict oldPtr = neighs; Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh)); cap = newCap; neighs = newPtr; memcpy(newPtr, oldPtr, deg * sizeof(Neigh)); globalAllocator.freePow2(oldPtr, newCap * 2 * sizeof(Neigh)); } } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt); } else{ //delete out edge deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, thInfo[actualTh].edgeCnt); } } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, el[i].weight, garbage); } else{ //delete in edge deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, garbage); } } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } //we do not need atomic operation on affected as long as "some" thread updates it if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert out edge insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, el[i].weight, thInfo[0].edgeCnt); //insert in edge insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, el[i].weight, garbage); } else{ //delete out edge deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, thInfo[0].edgeCnt); //delete in edge deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_CAHCE_FRIENDLY_HASH #include "GraphTangoHash.h" Vertex<Neigh>* vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>)); for(u64 i = 0; i < numNodes; i++){ Vertex<Neigh>& v = vArray[i]; v.inEdges.degree = 0; v.inEdges.capacity = NUM_INITIAL_ELEMS; v.inEdges.neighArr = v.inEdges.neigh; v.outEdges.degree = 0; v.outEdges.capacity = NUM_INITIAL_ELEMS; v.outEdges.neighArr = v.outEdges.neigh; } cout << "Size of GraphTangoHash: " << sizeof(GraphTangoHash<Neigh>) << endl; cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl; cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Size of Neigh: " << sizeof(Neigh) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ free(vArray); } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } //insert out edge vArray[src].outEdges.insert(dst, thInfo[actualTh].edgeCnt); } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } //insert in edge u64 garbage; vArray[dst].inEdges.insert(src, garbage); } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } //insert out edge vArray[src].outEdges.insert(dst, thInfo[0].edgeCnt); //insert in edge u64 garbage; vArray[dst].inEdges.insert(src, garbage); } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif #ifdef USE_CAHCE_FRIENDLY_HASH_ONLY #include "GraphTangoHash.h" Vertex<Neigh>* vArray; const int num_threads; typedef struct{ u64 edgeCnt = 0; u64 nodeCnt = 0; u8 pad[48]; } ThreadInfo; alignas(64) ThreadInfo thInfo[32]; GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){ #ifdef _OPENMP if(numThreads > 0){ omp_set_num_threads(numThreads); } #endif vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>)); for(u64 i = 0; i < numNodes; i++){ Vertex<Neigh>& v = vArray[i]; v.inEdges.degree = 0; v.inEdges.adjList = v.inEdges.neigh; //v.inEdges.capacity = NUM_INITIAL_ELEMS * 2; //v.inEdges.neighArr = v.inEdges.neigh; v.outEdges.degree = 0; v.outEdges.adjList = v.outEdges.neigh; //v.outEdges.capacity = NUM_INITIAL_ELEMS * 2; //v.outEdges.neighArr = v.outEdges.neigh; } cout << "Size of GraphTangoHash: " << sizeof(GraphTangoHash<Neigh>) << endl; cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl; cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl; cout << "Size of Neigh: " << sizeof(Neigh) << endl; property.resize(numNodes, -1); affected.resize(numNodes); affected.fill(false); } ~GraphTango(){ free(vArray); } int64_t in_degree(NodeID n) override { return vArray[n].inEdges.degree; } int64_t out_degree(NodeID n) override { return vArray[n].outEdges.degree; } void update(const EdgeList& el) override { const u64 batchSize = el.size(); #ifdef _OPENMP int thMask = (1 << getNextPow2Log2(num_threads)) - 1; #pragma omp parallel for(u64 i = 0; i < batchSize; i++){ const i64 src = el[i].source; const i64 dst = el[i].destination; const i64 actualTh = omp_get_thread_num(); i64 targetTh = (src / 64) & thMask; if(targetTh == actualTh){ if(!el[i].sourceExists){ thInfo[actualTh].nodeCnt++; } if(!el[i].destExists){ thInfo[actualTh].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insert(dst, thInfo[actualTh].edgeCnt); } else{ //delete out edge vArray[src].outEdges.erase(dst, thInfo[actualTh].edgeCnt); } } targetTh = (dst / 64) & thMask; if(targetTh == actualTh){ if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert in edge vArray[dst].inEdges.insert(src, garbage); } else{ //delete in edge vArray[dst].inEdges.erase(src, garbage); } } } #else for(u64 i = 0; i < batchSize; i++){ const u64 src = el[i].source; const u64 dst = el[i].destination; if(!el[i].sourceExists){ thInfo[0].nodeCnt++; } if(!el[i].destExists){ thInfo[0].nodeCnt++; } if(!affected[src]){ affected[src] = true; } if(!affected[dst]){ affected[dst] = true; } u64 garbage; if(!el[i].isDelete){ //insert out edge vArray[src].outEdges.insert(dst, thInfo[0].edgeCnt); //insert in edge vArray[dst].inEdges.insert(src, garbage); } else{ //delete out edge vArray[src].outEdges.erase(dst, thInfo[0].edgeCnt); //delete in edge vArray[dst].inEdges.erase(src, garbage); } } #endif for(u64 i = 0; i < num_threads; i++){ num_edges += thInfo[i].edgeCnt; thInfo[i].edgeCnt = 0; num_nodes += thInfo[i].nodeCnt; thInfo[i].nodeCnt = 0; } //num_nodes = el[batchSize - 1].lastAssignedId + 1; } #endif // void insertEdge(Idx srcId, Idx dstId, const EProp& eProp){ // const u64 deg = vArray.getOutDegree(srcId); // // if(__builtin_expect(deg == vArray.getCapacity(srcId), 0)){ // const u64 newCap = vArray.getCapacity(srcId) * 2; // // // Idx* __restrict dstOld = vArray.getDstIdArray(srcId); // //#ifdef HAS_EDGE_PROP // EProp* __restrict propOld = vSoA.ePropArr[offset]; // Idx* __restrict dstNew = (Idx*)globalAllocator.allocPow2(newCap * (sizeof(Idx) + sizeof(EProp))); // EProp* __restrict propNew = (EProp*)(dstNew + newCap); // //EProp* __restrict propNew = (EProp*)globalAllocator.allocPow2(newCap * sizeof(EProp)); //#else // Idx* __restrict dstNew = (Idx*)globalAllocator.allocPow2(newCap * sizeof(Idx)); //#endif // // for(U64 i = 0; i < deg; i++){ // dstNew[i] = dstOld[i]; //#ifdef HAS_EDGE_PROP // propNew[i] = propOld[i]; //#endif // } // //#ifdef HAS_EDGE_PROP // globalAllocator.freePow2(dstOld, newCap / 2 * (sizeof(Idx) + sizeof(EProp))); //#else // globalAllocator.freePow2(dstOld, newCap / 2 * (sizeof(Idx))); //#endif // //globalAllocator.freePow2(dstOld, newCap / 2 * sizeof(Idx)); // //globalAllocator.freePow2(propOld, newCap / 2 * sizeof(EProp)); // //#if defined(USE_FULL_HASHMAP) || defined(USE_HYBRID_HASH_V2) // vArray.dstLocMap[srcId][0].reserve(newCap); //#endif // vArray.setCapacity(srcId, newCap); // vArray.setDstIdArray(srcId, dstNew); //#ifdef HAS_EDGE_PROP // vSoA.ePropArr[offset] = propNew; //#endif // } // //#if defined(USE_FULL_HASHMAP) // vSoA.dstLocMap[offset][dstId] = deg; //#elif defined(USE_HYBRID_HASHMAP) // if(deg >= HYBRID_HASH_PARTITION) { // vSoA.dstLocMap[offset][dstId] = deg; // } //#elif defined(USE_HYBRID_HASH_V2) // if(vArray.dstLocMap[srcId] != nullptr) { // vArray.dstLocMap[srcId][0][dstId] = deg; // } // else if(deg >= HYBRID_HASH_THRESHOLD){ // vArray.dstLocMap[srcId] = new graphite_hashmap; // vArray.dstLocMap[srcId][0][dstId] = deg; // } // //#endif // // vArray.getDstIdArray(srcId)[deg] = dstId; //#ifdef HAS_EDGE_PROP // vSoA.ePropArr[offset][deg] = eProp; //#endif // vArray.getOutDegree(srcId)++; // } // void deleteEdge(Idx srcId, Idx dstId){ // Idx* __restrict dstIdArr = vArray.getDstIdArray(srcId); // //#ifdef HAS_EDGE_PROP // EProp* __restrict ePropArr = vSoA.ePropArr[offset]; //#endif // // if(vArray.getOutDegree(srcId)){ //#if defined(USE_FULL_HASHMAP) // const auto& dstIt = vSoA.dstLocMap[offset].find(dstId); // if(dstIt != vSoA.dstLocMap[offset].end()){ // const Idx dstLoc = dstIt->second; // vSoA.dstLocMap[offset].erase(dstIt); // const Idx outDeg = --vSoA.outDegree[offset]; // if(__builtin_expect(outDeg != dstLoc, 1)){ //not the last element // dstIdArr[dstLoc] = dstIdArr[outDeg]; //#ifdef HAS_EDGE_PROP // ePropArr[dstLoc] = ePropArr[outDeg]; //#endif // vSoA.dstLocMap[offset][dstIdArr[outDeg]] = dstLoc; // } // } //#elif defined(USE_SORTED_EDGES) // // First thing first, find the location of the dst node // const Idx outDeg = vSoA.outDegree[offset] - 1; // const Idx lastDstId = dstIdArr[outDeg]; // if(__builtin_expect(lastDstId != dstId, 1)){ //not the last element // const u64 sortedLen = vSoA.sortedLen[offset]; // u64 dstLoc = lower_bound(dstIdArr, dstIdArr + sortedLen, dstId) - dstIdArr; // if((dstLoc == sortedLen) || (dstIdArr[dstLoc] != dstId)){ //not found in the sorted region, linear search rest // dstLoc = sortedLen - 1; // while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg); // } // // if(__builtin_expect(dstLoc != outDeg, 1)){ // //found // dstIdArr[dstLoc] = dstIdArr[outDeg]; //#ifdef HAS_EDGE_PROP // ePropArr[dstLoc] = ePropArr[outDeg]; //#endif // vSoA.outDegree[offset]--; // } // } // else{ //last element // vSoA.outDegree[offset]--; // } // // // sorted len goes over the out degree. Adjust. // if(vSoA.sortedLen[offset] > vSoA.outDegree[offset]){ // vSoA.sortedLen[offset]--; // } // //#elif defined(USE_HYBRID_HASHMAP) // const u64 outDeg = vSoA.outDegree[offset] - 1; // // if(dstIdArr[outDeg] == dstId){ //last element // vSoA.outDegree[offset]--; // if(outDeg >= HYBRID_HASH_PARTITION){ // vSoA.dstLocMap[offset].erase(dstId); // } // return; // } // // // u64 dstLoc = -1; // // if(outDeg >= HYBRID_HASH_PARTITION){ // const auto& dstIt = vSoA.dstLocMap[offset].find(dstId); // if(dstIt != vSoA.dstLocMap[offset].end()){ // //found // dstLoc = dstIt->second; // vSoA.dstLocMap[offset].erase(dstIt); // } // } // // if(dstLoc == -1){ //not yet found, do linear search // while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg); // if(__builtin_expect(dstLoc == outDeg, 0)){ // //not found // return; // } // } // // // // //valid dstLoc // dstIdArr[dstLoc] = dstIdArr[outDeg]; //#ifdef HAS_EDGE_PROP // ePropArr[dstLoc] = ePropArr[outDeg]; //#endif // vSoA.dstLocMap[offset][dstIdArr[outDeg]] = dstLoc; // //#elif defined(USE_HYBRID_HASH_V2) // if(vArray.dstLocMap[srcId] == nullptr){ // //Not using hashmap // const Idx outDeg = vArray.getOutDegree(srcId) - 1; // Idx lastDstId = dstIdArr[outDeg]; // if(__builtin_expect(lastDstId != dstId, 1)){ //not the last element // u64 dstLoc = -1; // while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg); // if(__builtin_expect(dstLoc != outDeg, 1)){ // dstIdArr[dstLoc] = dstIdArr[outDeg]; //#ifdef HAS_EDGE_PROP // ePropArr[dstLoc] = ePropArr[outDeg]; //#endif // vArray.getOutDegree(srcId)--; // } // } // else{ // vArray.getOutDegree(srcId)--; //last element // } // } // else{ // //Using hashmap // const auto& dstIt = vArray.dstLocMap[srcId]->find(dstId); // if(dstIt != vArray.dstLocMap[srcId]->end()){ // const Idx dstLoc = dstIt->second; // vArray.dstLocMap[srcId]->erase(dstIt); // const Idx outDeg = --vArray.outDegree[srcId]; // if(__builtin_expect(outDeg != dstLoc, 1)){ //not the last element // dstIdArr[dstLoc] = dstIdArr[outDeg]; //#ifdef HAS_EDGE_PROP // ePropArr[dstLoc] = ePropArr[outDeg]; //#endif // vArray.dstLocMap[srcId][0][dstIdArr[outDeg]] = dstLoc; // } // } // } // //#else // const Idx outDeg = vArray.getOutDegree(srcId) - 1; // Idx lastDstId = dstIdArr[outDeg]; // if(__builtin_expect(lastDstId != dstId, 1)){ //not the last element // u64 dstLoc = -1; // while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg); // if(__builtin_expect(dstLoc != outDeg, 1)){ // dstIdArr[dstLoc] = dstIdArr[outDeg]; //#ifdef HAS_EDGE_PROP // ePropArr[dstLoc] = ePropArr[outDeg]; //#endif // vArray.getOutDegree(srcId)--; // } // } // else{ // vArray.getOutDegree(srcId)--; //last element // } //#endif // } // } // // void insertEdges(Idx srcId, U64 count, const Idx* __restrict dstIds, const EProp* __restrict eProps){ // Vertex& vv = vertices[srcId]; // VExtra& ve = vExtras[srcId]; // // if(ve.eCap < (vv.outDeg + count)){ // ve.eCap = getNextPow2(vv.outDeg + count); // Idx* __restrict dstOld = vv.dstArr; // EProp* __restrict propOld = vv.ePropArr; // vv.dstArr = (Idx*)aligned_alloc(64, ve.eCap * sizeof(Idx)); // vv.ePropArr = (EProp*)aligned_alloc(64, ve.eCap * sizeof(EProp)); // #pragma omp parallel for simd // for(U64 i = 0; i < vv.outDeg; i++){ // vv.dstArr[i] = dstOld[i]; // vv.ePropArr[i] = propOld[i]; // } // free(dstOld); // free(propOld); // ve.dstLocMap.reserve(ve.eCap); // } // #pragma omp parallel for // for(U64 i = 0; i < count; i++){ // vv.ePropArr[vv.outDeg + i] = eProps[i]; // vv.dstArr[vv.outDeg + i] = dstIds[i]; // ve.dstLocMap[dstIds[i]] = i; // } // vv.outDeg += count; // } //typedef const vProp_t& (*processEdgeFunc)(const eProp_t& eProp, const vProp_t& srcProp, const vProp_t& dstProp); //typedef const vProp_t& (*reduceFunc)(const vProp_t& temp, const vProp_t& res); //---------------------------------- VERTEX ------------------------------------------ /*inline I64 insertVertex(const VProp& vProp = 0){ if(deletedVertices.empty()){ vProps.push_back(vProp); outEdges.push_back(new EdgeArrayBlock<eProp_t>); //valid.push_back(true); return (vProps.size() - 1); } else{ I64 vidx = deletedVertices.top(); //valid[vidx] = true; deletedVertices.pop(); return vidx; } }*/ /*U64 insertManyVertex(U64 count){ U64 startId = vertices.size(); vertices.resize(startId + count); for(U64 i = 0; i < count; i++){ outEdges.push_back(new EdgeArrayBlock<eProp_t>); //outEdges.push_back(new EdgeArrayVector<eProp_t>); } return startId; }*/ // U64 insertManyVertex(const U64 count, const VProp& vProp = 0){ // const U64 startId = vSize; // const U64 endId = vSize + count; // if(vCap < endId){ // vCap = getNextPow2(endId); // Vertex* __restrict newVer = (Vertex*)aligned_alloc(64, vCap * sizeof(Vertex)); // VExtra* __restrict newExt = (VExtra*)aligned_alloc(64, vCap * sizeof(VExtra)); // #pragma omp parallel for simd // for(U64 i = 0; i < vSize; i++){ // newVer[i] = vertices[i]; // newExt[i] = vExtras[i]; // } // free(vertices); // free(vExtras); // vertices = newVer; // vExtras = newExt; // } // #pragma omp parallel for // for(U64 i = startId; i < endId; i++){ // vertices[i].prop = vProp; // vertices[i].outDeg = 0; // vExtras[i].eCap = getNextPow2(0); // vertices[i].dstArr = (Idx*)aligned_alloc(64, vExtras[i].eCap * sizeof(Idx)); // vertices[i].ePropArr = (EProp*)aligned_alloc(64, vExtras[i].eCap * sizeof(EProp)); // new (&vExtras[i].dstLocMap) std::unordered_map<Idx, U64>; // } // vSize = endId; // return startId; // } /*inline void deleteVertex(I64 vIdx){ //TODO const I64 cnt = valid.size(); for(I64 i = 0; i < cnt; i++){ if(valid[i]){ outEdges[i]->deleteEdge(vIdx); } } }*/ /*inline vProp_t& getVProp(I64 vIdx) { return vProps[vIdx]; } inline const vProp_t& getVProp(I64 vIdx) const { return vProps[vIdx]; } inline void setVProp(I64 vIdx, const vProp_t &vProp){ vProps[vIdx] = vProp; } inline U64 getVCount() const { return (vProps.size() - deletedVertices.size()); } //----------------------------------- EDGE ------------------------------------------- inline void insertEdge(I64 srcId, I64 dstId, const eProp_t &eProp = {}){ //eCount++; outEdges[srcId]->insertEdge(dstId, eProp); } inline void updateEdge(I64 srcId, I64 dstId, const eProp_t &eProp){ outEdges[srcId]->updateEdge(dstId, eProp); } inline void deleteEdge(I64 srcId, I64 dstId){ outEdges[srcId]->deleteEdge(dstId); //eCount--; } inline eProp_t& getEProp(I64 srcId, I64 dstId){ return outEdges[srcId]->getEProp(dstId); } inline const eProp_t& getEProp(I64 srcId, I64 dstId) const { return outEdges[srcId]->getEProp(dstId); } inline U64 getECount() const { return eCount; } inline auto getEdgeArray(I64 srcId){ return outEdges[srcId]; }*/ //----------------------------------- ANALYTICS -------------------------------------- /*void run_analysis_algo(processEdgeFunc processEdge, reduceFunc reduce){ while(!activeVertices.empty()){ processing_phase(processEdge, reduce); commit_phase(); } }*/ // void run_bfs(I64 rootIdx){ // typedef struct { // U64 outDeg; // Idx* dstArr; // } EdgeInfo; // // const U64 maxTh = omp_get_max_threads(); // // std::vector<EdgeInfo> q; // U64 qTail = 0; // // q.push_back({vertices[rootIdx].outDeg, vertices[rootIdx].dstArr}); // vertices[rootIdx].prop = 0; // // U64 iter = 1; // while((q.size() - qTail) < maxTh) { // const U64 qHeadOrig = q.size(); // for(U64 qT = qTail; qT < qHeadOrig; qT++){ // //pop qTail // const EdgeInfo oe = q[qT]; // for(U64 i = 0; i < oe.outDeg; i++){ // const I64 dstId = oe.dstArr[i]; // if(vertices[dstId].prop > iter){ // vertices[dstId].prop = iter; // q.push_back({vertices[dstId].outDeg, vertices[dstId].dstArr}); // } // } // } // qTail = qHeadOrig; // iter++; // } // // typedef struct { // std::vector<EdgeInfo> q; // U64 qTail; // U64 iter; // U8 pad[24]; // } ThQ; // // std::vector<ThQ> qVec(maxTh); // // // Initialize // for(U64 i = 0; i < maxTh; i++){ // qVec[i].qTail = 0; // qVec[i].iter = iter; // } // // //distribute vertices // U64 idx = 0; // for(U64 i = qTail; i < q.size(); i++){ // if(idx == maxTh){ // idx = 0; // } // qVec[idx].q.push_back(q[i]); // idx++; // } // // // #pragma omp parallel // { // U64 th = omp_get_thread_num(); // std::vector<EdgeInfo>& q = qVec[th].q; // U64& qTail = qVec[th].qTail; // U64& iter = qVec[th].iter; // while(q.size() - qTail) { // const U64 qHeadOrig = q.size(); // for(U64 qT = qTail; qT < qHeadOrig; qT++){ // //pop qTail // const EdgeInfo oe = q[qT]; // for(U64 i = 0; i < oe.outDeg; i++){ // const I64 dstId = oe.dstArr[i]; // if(vertices[dstId].prop > iter){ // vertices[dstId].prop = iter; // q.push_back({vertices[dstId].outDeg, vertices[dstId].dstArr}); // } // } // } // qTail = qHeadOrig; // iter++; // } // } // } // // void run_bfs_old(I64 rootIdx){ // typedef struct { // U64 outDeg; // Idx* dstArr; // } EdgeInfo; // // EdgeInfo* __restrict q = (EdgeInfo*)aligned_alloc(64, vSize * sizeof(EdgeInfo)); // U64 qHead = 1; // U64 qTail = 0; // // q[0] = {vertices[rootIdx].outDeg, vertices[rootIdx].dstArr}; // vertices[rootIdx].prop = 0; // // U64 iter = 1; // while(qHead - qTail) { // const U64 qHeadOrig = qHead; // #pragma omp parallel for // for(U64 qT = qTail; qT < qHeadOrig; qT++){ // //pop qTail // const EdgeInfo& oe = q[qT]; // for(U64 i = 0; i < oe.outDeg; i++){ // const I64 dstId = oe.dstArr[i]; // if(vertices[dstId].prop > iter){ // vertices[dstId].prop = iter; // U64 loc; // #pragma omp atomic capture // loc = qHead++; // q[loc] = {vertices[dstId].outDeg, vertices[dstId].dstArr}; // } // } // } // qTail = qHeadOrig; // iter++; // } // } /*void addVertexToWavefront(I64 vIdx){ activeVertices.push_back(vIdx); } inline void processing_phase(processEdgeFunc processEdge, reduceFunc reduce){ const U64 activeCount = activeVertices.size(); #pragma omp parallel for for(U64 i = 0; i < activeCount; i++){ I64 srcId = activeVertices[i]; auto outEdgeArr = outEdges[srcId]; const U64 outEdgeCount = outEdgeArr.size(); const vProp_t& srcProp = vProps[srcId]; for(U64 i = 0; i < outEdgeCount; i++){ const auto edge = outEdgeArr->edges[i]; const vProp_t& res = processEdge(edge.eProp, srcProp, vProps[edge.dstId]); vTempProps[edge.dstId] = reduce(vTempProps[edge.dstId], res); } } } inline void commit_phase(){ const U64 vertexCount = getVCount(); #pragma omp parallel for for(U64 i = 0; i < vertexCount; i++){ if(vProps[i] != vTempProps[i]){ vProps[i] = vTempProps[i]; omp_set_lock(&lock); activeVertices.push_back(i); omp_unset_lock(&lock); } } }*/ //----------------------------------- OTHERS ----------------------------------------- /*void compact(){ } void garbage_collection(){ }*/ //static GraphTango* buildFromTextCSR(const std::string &fname){ //} /*static u64 binSearch(const i64* sortedArr, i64 val, u64 s, u64 e){ if((e - s) <= 1){ i64 diffE = sortedArr[e * VECTOR_WIDTH] - val; i64 diffS = val - sortedArr[s * VECTOR_WIDTH]; if(diffE < diffS){ return e; } return s; } u64 mid = (s + e) / 2; u64 midVal = sortedArr[mid * VECTOR_WIDTH]; if(val == midVal){ return mid; } else if(val < midVal){ return binSearch(sortedArr, val, s, mid); } else { return binSearch(sortedArr, val, mid, e); } }*/ // static GraphTango* buildFromStingerCSR( // const i64 numThreads, // const U64 nv, // const U64 ne, // const I64* __restrict off, // const I64* __restrict ind, // const I64* __restrict weight, // const VProp& defaultProp = 0) // { // auto gra = new GraphTango<VProp, EProp>(numThreads); // // gra->vArray.resize(nv); // // //// //// ofstream outf("edgelist.txt"); //// for(u64 v = 0; v < nv; v++){ //// const U64 deg = off[v + 1] - off[v]; //// const I64* __restrict indE = ind + off[v]; //// const I64* __restrict wgtE = weight + off[v]; //// for(u64 e = 0; e < deg; e++){ //// outf << v << " " << indE[e] << "\n"; //// } //// } //// outf.close(); // //// struct { //// u64 e = 0; //// u8 pad[56]; //// } cnt[25]; //// //// //// const u64 perThEdge = ne / omp_get_max_threads(); //// const u64 nvVect = (nv + VECTOR_WIDTH - 1)/VECTOR_WIDTH; //// #pragma omp parallel //// { //// u64 th = omp_get_thread_num(); //// u64 target = (th + 1) * perThEdge; //// cnt[th+1].e = binSearch(off, target, 0, nvVect) * VECTOR_WIDTH; //// } //// //// auto& vArr = gra->vertexArray; //// #pragma omp parallel //// { //// const u64 th = omp_get_thread_num(); //// for(u64 v = cnt[th].e; v < cnt[th+1].e; v++){ //// VertexSoA<VProp, EProp>& vSoA = vArr[v / VECTOR_WIDTH]; //// const u64 offset = v % VECTOR_WIDTH; //// const U64 deg = off[v + 1] - off[v]; //// vSoA.outDegree[offset] = deg; //// //// const u64 cap = std::max(getNextPow2(deg), 4UL); //// vSoA.capacity[offset] = cap; //// //// vSoA.dstIdArr[offset] = (Idx*)globalAllocator.allocPow2(cap * sizeof(Idx)); //// vSoA.ePropArr[offset] = (EProp*)globalAllocator.allocPow2(cap * sizeof(EProp)); //// //vArr[v / VECTOR_WIDTH].dstIdArr[v % VECTOR_WIDTH] = (Idx*)aligned_alloc(64, cap * sizeof(Idx)); //// //vArr[v / VECTOR_WIDTH].ePropArr[v % VECTOR_WIDTH] = (EProp*)aligned_alloc(64, cap * sizeof(EProp)); //// //// new (&vSoA.dstLocMap[offset]) unordered_map<Idx, U64>; //// vSoA.dstLocMap[offset].reserve(deg); //// //// const I64* __restrict indE = ind + off[v]; //// const I64* __restrict wgtE = weight + off[v]; //// //// Idx* dstIdArr = vSoA.dstIdArr[offset]; //// EProp* ePropArr = vSoA.ePropArr[offset]; //// auto& dstLocMap = vSoA.dstLocMap[offset]; //// //// for(u64 e = 0; e < deg; e++){ //// ePropArr[e] = wgtE[e]; //// dstIdArr[e] = indE[e]; //// dstLocMap[ind[e]] = e; //// } //// //// } //// } // // auto& vArr = gra->vArray; // #pragma omp parallel for // for(u64 v = 0; v < nv; v++){ // const U64 deg = off[v + 1] - off[v]; // vArr.setOutDegree(v, deg); // vArr.setVProp(v, defaultProp); // const u64 cap = getNextPow2(deg); // vArr.setCapacity(v, cap); // //#ifdef HAS_EDGE_PROP // vSoA.dstIdArr[offset] = (Idx*)globalAllocator.allocPow2(cap * (sizeof(Idx) + sizeof(EProp))); // vSoA.ePropArr[offset] = (EProp*)(vSoA.dstIdArr[offset] + cap); // //vSoA.ePropArr[offset] = (EProp*)globalAllocator.allocPow2(cap * sizeof(EProp)); //#else // //vSoA.dstIdArr[offset] = (Idx*)globalAllocator.allocPow2(cap * sizeof(Idx)); // vArr.setDstIdArray(v, (Idx*)globalAllocator.allocPow2(cap * sizeof(Idx))); //#endif // // const I64* __restrict indE = ind + off[v]; // const I64* __restrict wgtE = weight + off[v]; // // I64* __restrict dstIdArr = vArr.getDstIdArray(v); //#ifdef HAS_EDGE_PROP // I64* __restrict ePropArr = vSoA.ePropArr[offset]; //#endif // // //#if defined(USE_FULL_HASHMAP) // auto& dstLocMap = vSoA.dstLocMap[offset]; // new (&dstLocMap) graphite_hashmap; // dstLocMap.reserve(cap); // for(u64 e = 0; e < deg; e++){ //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = indE[e]; // dstLocMap[ind[e]] = e; // } //#elif defined(USE_HYBRID_HASHMAP) // u64 linearRegion = std::min(deg, HYBRID_HASH_PARTITION); // for(u64 e = 0; e < linearRegion; e++){ //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = indE[e]; // } // auto& dstLocMap = vSoA.dstLocMap[offset]; // new (&dstLocMap) graphite_hashmap; // if(deg > HYBRID_HASH_PARTITION){ // dstLocMap.reserve(deg - HYBRID_HASH_PARTITION); // for(u64 e = HYBRID_HASH_PARTITION; e < deg; e++){ //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = indE[e]; // dstLocMap[ind[e]] = e; // } // } //#elif defined(USE_SORTED_EDGES) // for(u64 e = 0; e < deg; e++){ //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = indE[e]; // } // sort(dstIdArr, dstIdArr + deg); // vSoA.sortedLen[offset] = deg; //#elif defined(USE_HYBRID_HASH_V2) // if(deg < HYBRID_HASH_THRESHOLD){ // //Do not use hashmap // vArr.dstLocMap[v] = nullptr; // for(u64 e = 0; e < deg; e++){ // const Idx dstId = indE[e]; //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = dstId; // } // } // else{ // //Use hashmap // //vArr.dstLocMap[v] = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap)); // //new (&vArr.dstLocMap[v]) graphite_hashmap(); // vArr.dstLocMap[v] = new graphite_hashmap(); // for(u64 e = 0; e < deg; e++){ // const Idx dstId = indE[e]; //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = dstId; // vArr.dstLocMap[v][0][dstId] = e; // //vArr.dstLocMap[v]->at(dstId) = e; // } // } // //#else // for(u64 e = 0; e < deg; e++){ // const Idx dstId = indE[e]; //#ifdef HAS_EDGE_PROP // ePropArr[e] = wgtE[e]; //#endif // dstIdArr[e] = dstId; //#ifdef USE_INCOMING_EDGES // omp_set_lock(&vArr.lock[dstId]); // vArr.inEdges[dstId].push_back(v); // omp_unset_lock(&vArr.lock[dstId]); //#endif // } //#if defined(SORT_EDGES_AT_BUILD) // std::sort(dstIdArr, dstIdArr + deg); //#endif //#endif // } // // return gra; // } /*static GraphTango* buildFromCSC(const std::string &fname){ } static GraphTango* buildFromCOO(const std::string &fname){ }*/ // void streamStingerActions(U64 naction, const I64* __restrict__ actions){ // // std::vector<std::pair<u64, u64> > srcDst; // for(u64 i = 0; i < naction; i++){ // long src = actions[i*2]; // if(src >= 0){ // srcDst.push_back({actions[i*2], actions[i*2 + 1]}); // } // else{ // srcDst.push_back({~actions[i*2], ~actions[i*2 + 1]}); // } // // } // // cout << srcDst.size() << endl; // cout << "===========insertions============" << endl; // // u64 iter = 0; // u64 totEdge = 0; // double totElp = 0.0; // // u64 nv = vArray.vSize; // // while(1){ // iter++; // if(iter == 50){ // break; // } // // tic(); // for(u64 i = 0; i < 1024*1024; i++){ // insertEdge(srcDst[totEdge].first, srcDst[totEdge].second, 1); // totEdge++; // } // totElp += toc(); // // cout << totEdge / 1000000.0 / totElp << endl; // } // // // // // cout << "===========Deletions============" << endl; // // iter = 0; // totEdge = 0; // totElp = 0.0; // // while(1){ // iter++; // if(iter == 50){ // break; // } // // tic(); // for(u64 i = 0; i < 1024*1024; i++){ // deleteEdge(srcDst[totEdge].first, srcDst[totEdge].second); // totEdge++; // } // totElp += toc(); // // cout << totEdge / 1000000.0 / totElp << endl; // } // //Divide work // int numThreads = omp_get_max_threads(); // int maxTh = 1; // while(maxTh <= numThreads){ // maxTh *= 2; // } // maxTh--; // // #pragma omp parallel num_threads(maxTh + 1) // for(U64 i = 0; i < naction; i++) { // I64 src = actions[i * 2]; // const I64 mask = 0UL - ((src >> 63) & 1UL); // src = src ^ mask; // int mappedTh = src & maxTh; // if(omp_get_thread_num() == mappedTh){ // I64 dst = actions[i * 2 + 1] ^ mask; // if(mask == 0UL){ // insertEdge(src, dst, 1); // } // else{ // deleteEdge(src, dst); // } // } // } // } //similar to what is done by stinger (queue based) // u64 run_bfs_v1(const Idx& root){ // Idx* __restrict activeList = (Idx*)globalAllocator.allocate(vArray.vSize * sizeof(Idx)); // u64 qHead = 1; // u64 qTail = 0; // // activeList[0] = root; // vArray.setVProp(root, 0); // // U64 iter = 1; // while(qHead - qTail) { // const U64 qHeadOrig = qHead; // #pragma omp parallel for // for(U64 qT = qTail; qT < qHeadOrig; qT++){ // //pop qTail // const u64 vIdx = activeList[qT]; // const u64 outDeg = vArray.outDegree[vIdx]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[vIdx]; // for(U64 i = 0; i < outDeg; i++){ // const I64 dstId = dstIdArr[i]; // if(vArray.prop[dstId] > iter){ // vArray.prop[dstId] = iter; // U64 loc; // #pragma omp atomic capture // loc = qHead++; // activeList[loc] = dstId; // } // } // } // qTail = qHeadOrig; // iter++; // } // globalAllocator.deallocate(activeList, vArray.vSize * sizeof(Idx)); // return iter; // } // // // u64 run_bfs_v2(const Idx& root){ // const u64 numV = vArray.vSize; // // vector<bool> currAct(numV, 0); // vector<bool> nextAct(numV, 0); // // // vArray.setVProp(root, 0); // currAct[root] = 1; // // u64 iter = 1; // bool isChanged = true; // while(isChanged){ // isChanged = false; // #pragma omp parallel for num_threads(64) // for(u64 v = 0; v < vArray.vSize; v++){ // if(currAct[v]){ //active // currAct[v] = 0; // const u64 outDeg = vArray.outDegree[v]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[v]; // //how about using AVX here? // for(U64 i = 0; i < outDeg; i++){ // const I64 dstId = dstIdArr[i]; // if(vArray.prop[dstId] > iter){ // vArray.prop[dstId] = iter; // // make dstId active for next iter // if(nextAct[dstId] == 0){ //checking this condition reduces thrashing // nextAct[dstId] = 1; // } // isChanged = true; // } // } // } // } // swap(currAct, nextAct); // iter++; // } // // return iter; // } // // // u64 run_bfs_v3(const Idx& root){ // const u64 numV = vArray.vSize; // // vector<bool> currAct(numV, 0); // wavefront for the current iter // vector<bool> nextAct(numV, 0); // wavefront for the next iter // // currAct[root] = 1; // // u64 iter = 0; // bool isChanged = true; // while(isChanged){ // isChanged = false; // #pragma omp parallel for num_threads(32) // for(u64 v = 0; v < vArray.vSize; v++){ // if(__builtin_expect(currAct[v], 0)){ // currAct[v] = 0; // if(vArray.prop[v] > iter){ // vArray.prop[v] = iter; // isChanged = true; // const u64 outDeg = vArray.outDegree[v]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[v]; // for(U64 i = 0; i < outDeg; i++){ // if(nextAct[dstIdArr[i]] == 0){ //checking this condition should reduces thrashing // nextAct[dstIdArr[i]] = 1; // } // } // } // } // } // swap(currAct, nextAct); // iter++; // } // // return iter; // } // // // u64 run_bfs_v4(const Idx& root){ // const u64 numV = vArray.vSize; // // vector<bool> currAct(numV, 0); // wavefront for the current iter // vector<bool> nextAct(numV, 0); // wavefront for the next iter // vector<bool> visited(numV, 0); // records visited vertices // // currAct[root] = 1; // // u64 iter = 0; // bool isChanged = true; // while(isChanged){ // isChanged = false; // #pragma omp parallel for num_threads(32) // for(u64 v = 0; v < vArray.vSize; v++){ // if (currAct[v]){ // currAct[v] = 0; // vArray.prop[v] = iter; //update value // isChanged = true; // const u64 outDeg = vArray.outDegree[v]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[v]; // for(U64 e = 0; e < outDeg; e++){ // const u64 dstId = dstIdArr[e]; // if(visited[dstId] == 0){ // visited[dstId] = 1; // nextAct[dstId] = 1; // } // } // } // } // swap(currAct, nextAct); // iter++; // } // // return iter; // } // // // //queue with visited bitset // u64 run_bfs_v5(const Idx& root){ // setVPropAll(0xFFFF'FFFF'FFFF'FFFFUL); // const u64 numV = vArray.vSize; // // Idx* __restrict activeList = (Idx*)globalAllocator.allocate(numV * sizeof(Idx)); // vector<bool> visited(numV, 0); // records visited vertices // u64 qHead = 1; // u64 qTail = 0; // // activeList[0] = root; // vArray.setVProp(root, 0); // // U64 iter = 1; // while(qHead - qTail) { // const U64 qHeadOrig = qHead; // #pragma omp parallel for num_threads(32) // for(U64 qT = qTail; qT < qHeadOrig; qT++){ // //pop qTail // const u64 vIdx = activeList[qT]; // const u64 outDeg = vArray.outDegree[vIdx]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[vIdx]; // for(U64 i = 0; i < outDeg; i++){ // const I64 dstId = dstIdArr[i]; // if(!visited[dstId]){ // visited[dstId] = 1; // vArray.prop[dstId] = iter; // U64 loc; // #pragma omp atomic capture // loc = qHead++; // activeList[loc] = dstId; // } // } // } // qTail = qHeadOrig; // iter++; // } // globalAllocator.deallocate(activeList, vArray.vSize * sizeof(Idx)); // return iter; // } // // // // Same as stinger (incorrect version) // u64 run_page_rank_v1(VProp epsilon, VProp dampingfactor, u64 maxIter){ //using outgoing edges (push) // // setVPropAll(1.0 / vArray.vSize); // const VProp offset = (1.0 - dampingfactor) / vArray.vSize; // // VProp* vTemp = (VProp*)globalAllocator.allocate(vArray.vSize * sizeof(VProp)); // // u64 iter = 0; // VProp delta = 1.0; // // while(delta > epsilon && iter != maxIter){ // // delta = 0.0; // // //processing phase // #pragma omp parallel for reduction(+:delta) // for(u64 v = 0; v < vArray.vSize; v++){ // vTemp[v] = 0; // const u64 outDeg = vArray.outDegree[v]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[v]; // for(u64 e = 0; e < outDeg; e++){ // const Idx dstId = dstIdArr[e]; // //if(vArray.outDegree[dstId]){ //outDegree of dst can be zero // vTemp[v] += (vArray.prop[dstId] / vArray.outDegree[dstId]); // //} // } // vTemp[v] = vTemp[v] * dampingfactor + offset; // VProp myDelta = vTemp[v] - vArray.prop[v]; // if(myDelta < 0){ // myDelta = -myDelta; // } // delta += myDelta; // } // // //apply phase // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // vArray.prop[v] = vTemp[v]; // } // // iter++; // } // // return iter; // } // // // // correct version // u64 run_page_rank_v2(VProp epsilon, VProp dampingfactor, u64 maxIter){ //using outgoing edges (push) // // setVPropAll(1.0 / vArray.vSize); // // VProp* vTemp = (VProp*)globalAllocator.allocate(vArray.vSize * sizeof(VProp)); // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // vTemp[v] = 0; // } // // // u64 iter = 0; // // while(iter != maxIter){ // // //processing phase // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // const u64 outDeg = vArray.outDegree[v]; // if(outDeg){ // const VProp pushVal = vArray.prop[v] / outDeg; // const Idx* __restrict dstIdArr = vArray.dstIdArr[v]; // for(u64 e = 0; e < outDeg; e++){ // const u64 dstId = dstIdArr[e]; // #pragma omp atomic // vTemp[dstId] += pushVal; // } // } // } // // //apply phase // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // vArray.prop[v] = dampingfactor + (1 - dampingfactor) * vTemp[v]; // } // // iter++; // } // // return iter; // } // // // u64 run_connected_components_v1(){ // const u64 numV = vArray.vSize; // VProp* __restrict vProps = vArray.prop; // // #pragma omp parallel for // for(u64 v = 0; v < numV; v++){ // vProps[v] = v; // } // // while(1){ // bool isChanged = false; // #pragma omp parallel for // for(u64 v = 0; v < numV; v++){ // const u64 numE = vArray.outDegree[v]; // const Idx* __restrict dstIdArr = vArray.dstIdArr[v]; // for(u64 e = 0; e < numE; e++){ // const Idx dstId = dstIdArr[e]; // if(vProps[v] > vProps[dstId]){ // vProps[v] = vProps[dstId]; // isChanged = true; // } // } // } // // if(!isChanged){ // break; // } // // #pragma omp parallel for // for(u64 v = 0; v < numV; v++){ // while(vProps[v] != vProps[vProps[v]]){ // vProps[v] = vProps[vProps[v]]; // } // } // } // // u64 components = 1; // #pragma omp parallel for reduction(+:components) // for(u64 v = 1; v < numV; v++){ // if(vProps[v] == v){ // components++; // } // } // // return components; // } // // //#ifdef USE_INCOMING_EDGES // // correct version // u64 run_page_rank_v3(VProp epsilon, VProp dampingfactor, u64 maxIter){ //using incoming edges (pull) // // setVPropAll(1.0 / vArray.vSize); // VProp* vTemp = (VProp*)globalAllocator.allocate(vArray.vSize * sizeof(VProp)); // // u64 iter = 0; // // while(iter != maxIter){ // // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // if(vArray.outDegree[v]){ // vArray.prop[v] = vArray.prop[v] / vArray.outDegree[v]; // } // } // // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // VProp sum = 0.0; // const u64 inDeg = vArray.inEdges[v].size(); // const Idx* __restrict srcIdArr = vArray.inEdges[v].data(); // for(u64 e = 0; e < inDeg; e++){ // const Idx srcId = srcIdArr[e]; // sum += vArray.prop[srcId]; // } // vTemp[v] = dampingfactor + (1 - dampingfactor) * sum; // } // // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // vArray.prop[v] = vTemp[v]; // } // // iter++; // } // // return iter; // } // //#endif // // // // void setVPropAll(const VProp& vProp) { // #pragma omp parallel for // for(u64 v = 0; v < vArray.vSize; v++){ // vArray.prop[v] = vProp; // } // } };
DRB093-doall2-collapse-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. */ /* Two-dimensional array computation: collapse(2) is used to associate two loops with omp for. The corresponding loop iteration variables are private. */ int a[100][100]; int main() { int i,j; #pragma omp parallel for collapse(2) for (i=0;i<100;i++) for (j=0;j<100;j++) a[i][j] = i; #pragma omp parallel for collapse(2) for (i=0;i<100;i++) for (j=0;j<100;j++) a[i][j]=a[i][j]+1; for (i=0;i<100;i++) for (j=0;j<100;j++) printf("%d\n", a[i][j]); return 0; }
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] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<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; }
GB_unaryop__ainv_int64_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__ainv_int64_int16 // op(A') function: GB_tran__ainv_int64_int16 // C type: int64_t // A type: int16_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ int64_t z = (int64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT64 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int64_int16 ( int64_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__ainv_int64_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
GB_unop__identity_uint64_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__identity_uint64_fc32 // op(A') function: GB_unop_tran__identity_uint64_fc32 // C type: uint64_t // A type: GxB_FC32_t // cast: uint64_t cij = GB_cast_to_uint64_t ((double) crealf (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ uint64_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 = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = GB_cast_to_uint64_t ((double) crealf (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = GB_cast_to_uint64_t ((double) crealf (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint64_fc32 ( uint64_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] ; uint64_t z = GB_cast_to_uint64_t ((double) crealf (aij)) ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_uint64_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
tensor_cpu-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) 2014 by Contributors * \file tensor_cpu-inl.h * \brief implementation of CPU host code * \author Bing Xu, Tianqi Chen */ #ifndef MSHADOW_TENSOR_CPU_INL_H_ #define MSHADOW_TENSOR_CPU_INL_H_ #include <cstring> #include <functional> #include <utility> #include <vector> #include "./base.h" #include "./tensor.h" #include "./packet-inl.h" #include "./dot_engine-inl.h" namespace mshadow { template<> inline void InitTensorEngine<cpu>(int dev_id) { } template<> inline void ShutdownTensorEngine<cpu>(void) { } template<> inline void SetDevice<cpu>(int devid) { } template<> inline Stream<cpu> *NewStream<cpu>(bool create_blas_handle, bool create_dnn_handle, int dev_id) { return new Stream<cpu>(); } template<> inline void DeleteStream<cpu>(Stream<cpu> *stream) { delete stream; } template<int ndim> inline std::ostream &operator<<(std::ostream &os, const Shape<ndim> &shape) { // NOLINT(*) os << '('; for (int i = 0; i < ndim; ++i) { if (i != 0) os << ','; os << shape[i]; } // python style tuple if (ndim == 1) os << ','; os << ')'; return os; } template<typename xpu> inline void *AllocHost_(size_t size); template<typename xpu> inline void FreeHost_(void * dptr); #ifdef __CUDACC__ template<> inline void *AllocHost_<gpu>(size_t size) { void *dptr; MSHADOW_CUDA_CALL(cudaMallocHost(&dptr, size, cudaHostAllocPortable)); return dptr; } template<> inline void FreeHost_<gpu>(void *dptr) { MSHADOW_CUDA_CALL(cudaFreeHost(dptr)); } #endif template<> inline void *AllocHost_<cpu>(size_t size) { size_t pitch; return packet::AlignedMallocPitch(&pitch, size, 1); } template<> inline void FreeHost_<cpu>(void *dptr) { packet::AlignedFree(dptr); } template<typename xpu, int dim, typename DType> inline void AllocHost(Tensor<cpu, dim, DType> *obj) { obj->stride_ = obj->size(dim - 1); CHECK_EQ(obj->CheckContiguous(), true) << "AllocHost"; void *dptr = AllocHost_<xpu>(obj->MSize() * sizeof(DType)); obj->dptr_ = reinterpret_cast<DType*>(dptr); } template<typename xpu, int dim, typename DType> inline void FreeHost(Tensor<cpu, dim, DType> *obj) { if (obj->dptr_ == NULL) { LOG(FATAL) << "FreeHost:: double free"; } FreeHost_<xpu>(obj->dptr_); obj->dptr_ = NULL; } template<int dim, typename DType> inline void AllocSpace(Tensor<cpu, dim, DType> *obj, bool pad) { size_t pitch; void *dptr; if (pad) { dptr = packet::AlignedMallocPitch (&pitch, obj->size(dim - 1) * sizeof(DType), obj->shape_.FlatTo2D()[0]); obj->stride_ = static_cast<index_t>(pitch / sizeof(DType)); } else { obj->stride_ = obj->size(dim - 1); dptr = packet::AlignedMallocPitch (&pitch, obj->shape_.Size() * sizeof(DType), 1); } obj->dptr_ = reinterpret_cast<DType*>(dptr); } template<typename Device, typename DType, int dim> inline Tensor<Device, dim, DType> NewTensor(const Shape<dim> &shape, DType initv, bool pad, Stream<Device> *stream_) { Tensor<Device, dim, DType> obj(shape); obj.stream_ = stream_; AllocSpace(&obj, pad); MapExp<sv::saveto>(&obj, expr::ScalarExp<DType>(initv)); return obj; } template<int dim, typename DType> inline void FreeSpace(Tensor<cpu, dim, DType> *obj) { packet::AlignedFree(obj->dptr_); obj->dptr_ = NULL; } template<int dim, typename DType> inline void Copy(Tensor<cpu, dim, DType> _dst, const Tensor<cpu, dim, DType> &_src, Stream<cpu> *stream) { #pragma GCC diagnostic push #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" #endif CHECK_EQ(_dst.shape_, _src.shape_) << "Copy:shape mismatch:" << _dst.shape_ << " vs " << _src.shape_; if (_dst.CheckContiguous() && _src.CheckContiguous()) { memcpy(_dst.dptr_, _src.dptr_, sizeof(DType) * _dst.shape_.Size()); } else { Tensor<cpu, 2, DType> dst = _dst.FlatTo2D(); Tensor<cpu, 2, DType> src = _src.FlatTo2D(); for (index_t y = 0; y < dst.size(0); ++y) { memcpy(dst[y].dptr_, src[y].dptr_, sizeof(DType) * dst.size(1)); } } #pragma GCC diagnostic pop } template<typename Saver, typename R, int dim, typename DType, typename E> inline void MapPlan(TRValue<R, cpu, dim, DType> *dst, const expr::Plan<E, DType> &plan) { Shape<2> shape = expr::ShapeCheck<dim, R>::Check(dst->self()).FlatTo2D(); expr::Plan<R, DType> dplan = expr::MakePlan(dst->self()); #ifndef __CUDACC__ #pragma omp parallel for #endif // temp remove openmp, as default setting throttles CPU for (openmp_index_t y = 0; y < shape[0]; ++y) { for (index_t x = 0; x < shape[1]; ++x) { // trust your compiler! -_- they will optimize it Saver::template Save<DType>(dplan.REval(y, x), plan.Eval(y, x)); } } } // code to handle SSE optimization template<bool pass_check, typename Saver, typename R, int dim, typename DType, typename E, int etype> struct MapExpCPUEngine { inline static void Map(TRValue<R, cpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { MapPlan<Saver>(dst, MakePlan(exp.self())); } }; template<typename SV, int dim, typename DType, typename E, int etype> struct MapExpCPUEngine<true, SV, Tensor<cpu, dim, DType>, dim, DType, E, etype> { inline static void Map(Tensor<cpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { if (expr::PacketAlignCheck<dim, E, MSHADOW_DEFAULT_PACKET>::Check(exp.self()) && expr::PacketAlignCheck<dim, Tensor<cpu, dim, DType>, MSHADOW_DEFAULT_PACKET>::Check(*dst)) { expr::MapPacketPlan<SV>(dst->self(), expr::MakePacketPlan<MSHADOW_DEFAULT_PACKET>(exp.self())); } else { MapPlan<SV>(dst, MakePlan(exp.self())); } } }; template<typename Saver, typename R, int dim, typename DType, typename E, int etype> inline void MapExp(TRValue<R, cpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { expr::TypeCheckPass<expr::TypeCheck<cpu, dim, DType, E>::kMapPass> ::Error_All_Tensor_in_Exp_Must_Have_Same_Type(); Shape<dim> eshape = expr::ShapeCheck<dim, E>::Check(exp.self()); Shape<dim> dshape = expr::ShapeCheck<dim, R>::Check(dst->self()); CHECK(eshape[0] == 0 || eshape == dshape) << "Assignment: Shape of Tensors are not consistent with target, " << "eshape: " << eshape << " dshape:" << dshape; MapExpCPUEngine<expr::PacketCheck<E, MSHADOW_DEFAULT_PACKET>::kPass, Saver, R, dim, DType, E, etype> ::Map(dst->ptrself(), exp); } template<typename Saver, typename Reducer, typename R, typename DType, typename E, int etype> inline void MapReduceKeepLowest(TRValue<R, cpu, 1, DType> *dst, const expr::Exp<E, DType, etype> &exp, DType scale) { expr::TypeCheckPass<expr::TypeCheck<cpu, 1, DType, E>::kRedPass> ::Error_TypeCheck_Not_Pass_For_Reduce_Exp(); Shape<2> eshape = expr::ShapeCheck<expr::ExpInfo<E>::kDim, E> ::Check(exp.self()).FlatTo2D(); Shape<1> dshape = expr::ShapeCheck<1, R>::Check(dst->self()); CHECK_EQ(eshape[1], dshape[0]) << "MapReduceKeepLowest::reduction dimension do not match"; CHECK_NE(eshape[0], 0U) << "can not reduce over empty tensor"; // execution expr::Plan<R, DType> dplan = MakePlan(dst->self()); expr::Plan<E, DType> splan = MakePlan(exp.self()); #ifndef __CUDACC__ #pragma omp parallel for #endif for (openmp_index_t x = 0; x < eshape[1]; ++x) { DType res = splan.Eval(0, x); for (index_t y = 1; y < eshape[0]; ++y) { Reducer::Reduce(res, splan.Eval(y, x)); } Saver::template Save<DType>(dplan.REval(0, x), res * scale); } } template<typename Saver, typename Reducer, int dimkeep, typename R, typename DType, typename E, int etype> inline void MapReduceKeepHighDim(TRValue<R, cpu, 1, DType> *dst, const expr::Exp<E, DType, etype> &exp, DType scale) { expr::TypeCheckPass<expr::TypeCheck<cpu, dimkeep, DType, E>::kRedPass> ::Error_TypeCheck_Not_Pass_For_Reduce_Exp(); typedef Shape<expr::ExpInfo<E>::kDim> EShape; EShape eshape = expr::ShapeCheck<expr::ExpInfo<E>::kDim, E> ::Check(exp.self()); Shape<1> dshape = expr::ShapeCheck<1, R>::Check(dst->self()); CHECK_EQ(eshape[dimkeep], dshape[0]) << "MapReduceKeepHighDim::reduction dimension do not match"; // use equvalent form Shape<4> pshape = Shape4(eshape.ProdShape(0, dimkeep), eshape[dimkeep], eshape.ProdShape(dimkeep + 1, EShape::kSubdim), eshape[EShape::kSubdim]); // execution expr::Plan<R, DType> dplan = MakePlan(dst->self()); expr::Plan<E, DType> splan = MakePlan(exp.self()); #ifndef __CUDACC__ #pragma omp parallel for #endif for (openmp_index_t c = 0; c < pshape[1]; ++c) { DType res; Reducer::SetInitValue(res); for (index_t n = 0; n < pshape[0]; ++n) { DType tres; Reducer::SetInitValue(tres); for (index_t y = 0; y < pshape[2]; ++y) { for (index_t x = 0; x < pshape[3]; ++x) { Reducer::Reduce(tres, splan.Eval((n * pshape[1] + c) * pshape[2] + y, x)); } } Reducer::Reduce(res, tres); } Saver::template Save<DType>(dplan.REval(0, c), DType(res * scale)); } } template<typename DType> inline void Softmax(Tensor<cpu, 1, DType> dst, const Tensor<cpu, 1, DType> &energy) { DType mmax = energy[0]; for (index_t x = 1; x < dst.size(0); ++x) { if (mmax < energy[x]) mmax = energy[x]; } DType sum = DType(0.0f); for (index_t x = 0; x < dst.size(0); ++x) { dst[x] = std::exp(energy[x] - mmax); sum += dst[x]; } for (index_t x = 0; x < dst.size(0); ++x) { dst[x] /= sum; } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &src, const Tensor<cpu, 1, DType> &label) { #pragma omp parallel for for (openmp_index_t y = 0; y < dst.size(0); ++y) { const index_t k = static_cast<int>(label[y]); for (index_t x = 0; x < dst.size(1); ++x) { if (x == k) { dst[y][k] = src[y][k] - 1.0f; } else { dst[y][x] = src[y][x]; } } } } template<typename DType> inline void SmoothSoftmaxGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &src, const Tensor<cpu, 1, DType> &label, const float alpha) { const float smooth_grad = (alpha / (dst.size(1) - 1)); #pragma omp parallel for for (openmp_index_t y = 0; y < dst.size(0); ++y) { const index_t k = static_cast<int>(label[y]); for (index_t x = 0; x < dst.size(1); ++x) { if (x == k) { dst[y][k] = src[y][k] - 1.0f + alpha; } else { dst[y][x] = src[y][x] - smooth_grad; } } } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &src, const Tensor<cpu, 1, DType> &label, const DType &ignore_label) { #pragma omp parallel for for (openmp_index_t y = 0; y < dst.size(0); ++y) { const int k = static_cast<int>(label[y]); for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { if (static_cast<int>(ignore_label) == k) { dst[y][x] = 0.0f; } else { if (x == k) { dst[y][k] = src[y][k] - 1.0f; } else { dst[y][x] = src[y][x]; } } } } } template<typename DType> inline void SmoothSoftmaxGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &src, const Tensor<cpu, 1, DType> &label, const DType &ignore_label, const float alpha) { const float smooth_grad = (alpha / (dst.size(1) - 1)); #pragma omp parallel for for (openmp_index_t y = 0; y < dst.size(0); ++y) { const int k = static_cast<int>(label[y]); for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { if (static_cast<int>(ignore_label) == k) { dst[y][x] = 0.0f; } else { if (x == k) { dst[y][k] = src[y][k] - 1.0f + alpha; } else { dst[y][x] = src[y][x] - smooth_grad; } } } } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &src, const Tensor<cpu, 2, DType> &label) { #pragma omp parallel for for (openmp_index_t n = 0; n < dst.size(2); ++n) { for (index_t y = 0; y < dst.size(0); ++y) { const int k = static_cast<int>(label[y][n]); for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { if (x == k) { dst[y][k][n] = src[y][k][n] - 1.0f; } else { dst[y][x][n] = src[y][x][n]; } } } } } template<typename DType> inline void SmoothSoftmaxGrad(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &src, const Tensor<cpu, 2, DType> &label, const float alpha) { const float smooth_grad = (alpha / (dst.size(1) - 1)); #pragma omp parallel for for (openmp_index_t n = 0; n < dst.size(2); ++n) { for (index_t y = 0; y < dst.size(0); ++y) { const int k = static_cast<int>(label[y][n]); for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { if (x == k) { dst[y][k][n] = src[y][k][n] - 1.0f + alpha; } else { dst[y][x][n] = src[y][x][n] - smooth_grad; } } } } } template<typename DType> inline void SoftmaxGrad(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &src, const Tensor<cpu, 2, DType> &label, const DType &ignore_label) { #pragma omp parallel for for (openmp_index_t n = 0; n < dst.size(2); ++n) { for (index_t y = 0; y < dst.size(0); ++y) { const int k = static_cast<int>(label[y][n]); if (k == static_cast<int>(ignore_label)) { for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { dst[y][x][n] = DType(0.0f); } } else { for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { if (x == k) { dst[y][k][n] = src[y][k][n] - 1.0f; } else { dst[y][x][n] = src[y][x][n]; } } } } } } template<typename DType> inline void SmoothSoftmaxGrad(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &src, const Tensor<cpu, 2, DType> &label, const DType &ignore_label, const float alpha) { const float smooth_grad = (alpha / (dst.size(1) - 1)); #pragma omp parallel for for (openmp_index_t n = 0; n < dst.size(2); ++n) { for (index_t y = 0; y < dst.size(0); ++y) { const int k = static_cast<int>(label[y][n]); if (k == static_cast<int>(ignore_label)) { for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { dst[y][x][n] = DType(0.0f); } } else { for (int x = 0; x < static_cast<int>(dst.size(1)); ++x) { if (x == k) { dst[y][k][n] = src[y][k][n] - 1.0f + alpha; } else { dst[y][x][n] = src[y][x][n] - smooth_grad; } } } } } } template<typename DType> inline void Softmax(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 2, DType> &energy) { CHECK_EQ(dst.shape_, energy.shape_) << "Softmax: shape mismatch"; #pragma omp parallel for for (openmp_index_t y = 0; y < dst.size(0); ++y) { Softmax(dst[y], energy[y]); } } template<typename DType> inline void Softmax(Tensor<cpu, 3, DType> dst, const Tensor<cpu, 3, DType> &energy) { CHECK_EQ(dst.shape_, energy.shape_) << "Softmax: shape mismatch"; #pragma omp parallel for for (openmp_index_t y = 0; y < dst.size(0); ++y) { for (index_t n = 0; n < dst.size(2); ++n) { DType mmax = energy[y][0][n]; for (index_t x = 1; x < dst.size(1); ++x) { if (mmax < energy[y][x][n]) mmax = energy[y][x][n]; } DType sum = DType(0.0f); for (index_t x = 0; x < dst.size(1); ++x) { dst[y][x][n] = std::exp(energy[y][x][n] - mmax); sum += dst[y][x][n]; } for (index_t x = 0; x < dst.size(1); ++x) { dst[y][x][n] /= sum; } } } } template<bool clip, typename IndexType, typename DType> inline void AddTakeGrad(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 1, IndexType>& index, const Tensor<cpu, 2, DType> &src) { const index_t K = dst.shape_[0]; const index_t C = dst.shape_[1]; for (index_t y = 0; y < index.size(0); ++y) { index_t j = index[y]; if (clip) { if (j <= 0) j = 0; else if (j >= K) j = K - 1; } else { j %= K; if (j < 0) j += K; } for (index_t i = 0; i < C; ++i) { dst[j][i] += src[y][i]; } } } // safe accumulation template<bool clip, typename IndexType, typename DType, typename AType> inline void AddTakeGrad(Tensor<cpu, 2, DType> dst, Tensor<cpu, 2, AType> temp, const Tensor<cpu, 1, IndexType>& index, const Tensor<cpu, 2, DType> &src) { const index_t K = dst.shape_[0]; const index_t C = dst.shape_[1]; for (index_t j = 0; j < K; ++j) { for (index_t i = 0; i < C; ++i) { temp[j][i] = dst[j][i]; } } for (index_t y = 0; y < index.size(0); ++y) { index_t j = index[y]; if (clip) { if (j <= 0) j = 0; else if (j >= K) j = K - 1; } else { j %= K; if (j < 0) j += K; } for (index_t i = 0; i < C; ++i) { temp[j][i] += src[y][i]; } } for (index_t j = 0; j < K; ++j) { for (index_t i = 0; i < C; ++i) { dst[j][i] = temp[j][i]; } } } template<typename IndexType, typename DType> inline void AddTakeGradLargeBatch(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 1, IndexType>& sorted, const Tensor<cpu, 1, IndexType>& index, const Tensor<cpu, 2, DType> &src) { for (index_t y = 0; y < sorted.size(0); ++y) { dst[sorted[y]] += src[index[y]]; } } template<typename IndexType, typename DType> inline void IndexFill(Tensor<cpu, 2, DType> dst, const Tensor<cpu, 1, IndexType>& index, const Tensor<cpu, 2, DType> &src) { for (index_t y = 0; y < index.size(0); ++y) { for (index_t j = 0; j < src.size(1); j++) { dst[index[y]][j] = src[y][j]; } } } template<typename KDType, typename VDType> inline void SortByKey(Tensor<cpu, 1, KDType> keys, Tensor<cpu, 1, VDType> values, bool is_ascend) { CHECK_EQ(keys.CheckContiguous(), true); CHECK_EQ(values.CheckContiguous(), true); CHECK_EQ(keys.size(0), values.size(0)) << "The sizes of key/value are not equal! keys_size: " << keys.size(0) << "values_size: " << values.size(0); std::vector<size_t> idx(keys.size(0)); std::vector<KDType> keys_vec(keys.size(0)); std::vector<VDType> values_vec(values.size(0)); for (int i = 0; i < keys.size(0); i++) { idx[i] = i; keys_vec[i] = keys[i]; values_vec[i] = values[i]; } if (is_ascend) { std::stable_sort(idx.begin(), idx.end(), [&keys_vec](size_t i1, size_t i2) {return keys_vec[i1] < keys_vec[i2]; }); } else { std::stable_sort(idx.begin(), idx.end(), [&keys_vec](size_t i1, size_t i2) {return keys_vec[i1] > keys_vec[i2]; }); } for (index_t i = 0; i < values.size(0); i++) { keys[i] = keys_vec[idx[i]]; values[i] = values_vec[idx[i]]; } } template<typename Device, typename VDType, typename SDType> inline void VectorizedSort(Tensor<Device, 1, VDType> values, Tensor<Device, 1, SDType> segments) { // We can sort each segments using two stable sorts SortByKey(values, segments, true); SortByKey(segments, values, true); } // blas related template<typename Device, typename DType> inline void VectorDot(Tensor<Device, 1, DType> dst, const Tensor<Device, 1, DType> &lhs, const Tensor<Device, 1, DType> &rhs) { CHECK_EQ(lhs.size(0), rhs.size(0)) << "VectorDot: Shape mismatch"; CHECK_EQ(dst.size(0), 1U) << "VectorDot: expect dst to be scalar"; expr::BLASEngine<Device, DType>::SetStream(lhs.stream_); mshadow::expr::BLASEngine<Device, DType>::dot( lhs.stream_, lhs.size(0), lhs.dptr_, 1, rhs.dptr_, 1, dst.dptr_); } template<bool transpose_left, bool transpose_right, typename Device, typename DType> inline void BatchGEMM(Tensor<Device, 3, DType> dst, const Tensor<Device, 3, DType> &lhs, const Tensor<Device, 3, DType> &rhs, DType alpha, DType beta, Tensor<Device, 1, DType*> workspace) { index_t batch_size = dst.shape_[0]; expr::BLASEngine<Device, DType>::SetStream(dst.stream_); Shape<3> sleft = transpose_left ? Shape3(lhs.shape_[0], lhs.shape_[2], lhs.shape_[1]) : lhs.shape_; Shape<3> sright = transpose_right ? Shape3(rhs.shape_[0], rhs.shape_[2], rhs.shape_[1]) : rhs.shape_; CHECK_EQ(dst.CheckContiguous(), true); CHECK_EQ(lhs.CheckContiguous(), true); CHECK_EQ(rhs.CheckContiguous(), true); CHECK(sleft[0] == batch_size && sright[0] == batch_size) << "BatchGEMM: batchsize must be equal." << "dst: " << dst.shape_ << "\n" << "lhs: " << sleft << "\n" << "rhs: " << sright << "\n"; CHECK(dst.size(1) == sleft[1] && dst.size(2) == sright[2] && sleft[2] == sright[1]) << "BatchGEMM: matrix shape mismatch" << "dst: " << dst.shape_ << "\n" << "lhs: " << sleft << "\n" << "rhs: " << sright << "\n"; CHECK(workspace.size(0) >= 3 * batch_size) << "Workspace Size must be bigger than " << 3 * batch_size; CHECK_EQ(workspace.CheckContiguous(), true); // use column major argument to compatible with most BLAS expr::BLASEngine<Device, DType>::batched_gemm (dst.stream_, transpose_right, transpose_left, transpose_right ? rhs.size(1) : rhs.size(2), transpose_left ? lhs.size(2) : lhs.size(1), transpose_right ? rhs.size(2) : rhs.size(1), alpha, rhs.dptr_, rhs.stride_, lhs.dptr_, lhs.stride_, beta, dst.dptr_, dst.stride_, batch_size, workspace.dptr_); } } // namespace mshadow #endif // MSHADOW_TENSOR_CPU_INL_H_
convolution_3x3_pack1to8_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_pack1to8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); float16x8_t _bias0 = bias ? vld1q_f16(bias + p * 8) : vdupq_n_f16((__fp16)0.f); out0.fill(_bias0); const __fp16* k0 = kernel.channel(p); int q = 0; for (; q < inch; q++) { __fp16* outptr0 = out0; const Mat img0 = bottom_blob.channel(q); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); float16x8_t _k00 = vld1q_f16(k0); float16x8_t _k01 = vld1q_f16(k0 + 8); float16x8_t _k02 = vld1q_f16(k0 + 16); float16x8_t _k10 = vld1q_f16(k0 + 24); float16x8_t _k11 = vld1q_f16(k0 + 32); float16x8_t _k12 = vld1q_f16(k0 + 40); float16x8_t _k20 = vld1q_f16(k0 + 48); float16x8_t _k21 = vld1q_f16(k0 + 56); float16x8_t _k22 = vld1q_f16(k0 + 64); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v24.8h, v25.8h, v26.8h, v27.8h}, [%0], #64 \n" // sum0 sum1 sum2 sum3 "prfm pldl1keep, [%0, #512] \n" "ld1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%0] \n" // sum4 sum5 sum6 sum7 "sub %0, %0, #64 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v0.8h}, [%1], #16 \n" // r0 "ld1 {v1.4h}, [%1] \n" "fmla v24.8h, %8.8h, v0.h[0] \n" "fmla v25.8h, %8.8h, v0.h[1] \n" "fmla v26.8h, %8.8h, v0.h[2] \n" "fmla v27.8h, %8.8h, v0.h[3] \n" "fmla v28.8h, %8.8h, v0.h[4] \n" "fmla v29.8h, %8.8h, v0.h[5] \n" "fmla v30.8h, %8.8h, v0.h[6] \n" "fmla v31.8h, %8.8h, v0.h[7] \n" "fmla v24.8h, %9.8h, v0.h[1] \n" "fmla v25.8h, %9.8h, v0.h[2] \n" "fmla v26.8h, %9.8h, v0.h[3] \n" "fmla v27.8h, %9.8h, v0.h[4] \n" "fmla v28.8h, %9.8h, v0.h[5] \n" "fmla v29.8h, %9.8h, v0.h[6] \n" "fmla v30.8h, %9.8h, v0.h[7] \n" "fmla v31.8h, %9.8h, v1.h[0] \n" "fmla v24.8h, %10.8h, v0.h[2] \n" "fmla v25.8h, %10.8h, v0.h[3] \n" "fmla v26.8h, %10.8h, v0.h[4] \n" "fmla v27.8h, %10.8h, v0.h[5] \n" "fmla v28.8h, %10.8h, v0.h[6] \n" "fmla v29.8h, %10.8h, v0.h[7] \n" "fmla v30.8h, %10.8h, v1.h[0] \n" "fmla v31.8h, %10.8h, v1.h[1] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v2.8h}, [%2], #16 \n" // r1 "ld1 {v3.4h}, [%2] \n" "fmla v24.8h, %11.8h, v2.h[0] \n" "fmla v25.8h, %11.8h, v2.h[1] \n" "fmla v26.8h, %11.8h, v2.h[2] \n" "fmla v27.8h, %11.8h, v2.h[3] \n" "fmla v28.8h, %11.8h, v2.h[4] \n" "fmla v29.8h, %11.8h, v2.h[5] \n" "fmla v30.8h, %11.8h, v2.h[6] \n" "fmla v31.8h, %11.8h, v2.h[7] \n" "fmla v24.8h, %12.8h, v2.h[1] \n" "fmla v25.8h, %12.8h, v2.h[2] \n" "fmla v26.8h, %12.8h, v2.h[3] \n" "fmla v27.8h, %12.8h, v2.h[4] \n" "fmla v28.8h, %12.8h, v2.h[5] \n" "fmla v29.8h, %12.8h, v2.h[6] \n" "fmla v30.8h, %12.8h, v2.h[7] \n" "fmla v31.8h, %12.8h, v3.h[0] \n" "fmla v24.8h, %13.8h, v2.h[2] \n" "fmla v25.8h, %13.8h, v2.h[3] \n" "fmla v26.8h, %13.8h, v2.h[4] \n" "fmla v27.8h, %13.8h, v2.h[5] \n" "fmla v28.8h, %13.8h, v2.h[6] \n" "fmla v29.8h, %13.8h, v2.h[7] \n" "fmla v30.8h, %13.8h, v3.h[0] \n" "fmla v31.8h, %13.8h, v3.h[1] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v4.8h}, [%3], #16 \n" // r2 "ld1 {v5.4h}, [%3] \n" "fmla v24.8h, %14.8h, v4.h[0] \n" "fmla v25.8h, %14.8h, v4.h[1] \n" "fmla v26.8h, %14.8h, v4.h[2] \n" "fmla v27.8h, %14.8h, v4.h[3] \n" "fmla v28.8h, %14.8h, v4.h[4] \n" "fmla v29.8h, %14.8h, v4.h[5] \n" "fmla v30.8h, %14.8h, v4.h[6] \n" "fmla v31.8h, %14.8h, v4.h[7] \n" "fmla v24.8h, %15.8h, v4.h[1] \n" "fmla v25.8h, %15.8h, v4.h[2] \n" "fmla v26.8h, %15.8h, v4.h[3] \n" "fmla v27.8h, %15.8h, v4.h[4] \n" "fmla v28.8h, %15.8h, v4.h[5] \n" "fmla v29.8h, %15.8h, v4.h[6] \n" "fmla v30.8h, %15.8h, v4.h[7] \n" "fmla v31.8h, %15.8h, v5.h[0] \n" "fmla v24.8h, %16.8h, v4.h[2] \n" "fmla v25.8h, %16.8h, v4.h[3] \n" "fmla v26.8h, %16.8h, v4.h[4] \n" "fmla v27.8h, %16.8h, v4.h[5] \n" "fmla v28.8h, %16.8h, v4.h[6] \n" "fmla v29.8h, %16.8h, v4.h[7] \n" "fmla v30.8h, %16.8h, v5.h[0] \n" "fmla v31.8h, %16.8h, v5.h[1] \n" "st1 {v24.8h, v25.8h, v26.8h, v27.8h}, [%0], #64 \n" "st1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; j + 3 < outw; j += 4) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%0] \n" // sum0 sum1 sum2 sum3 "prfm pldl1keep, [%1, #128] \n" "ld1 {v0.8h}, [%1] \n" // r0 "fmla v28.8h, %8.8h, v0.h[0] \n" "fmla v29.8h, %8.8h, v0.h[1] \n" "fmla v30.8h, %8.8h, v0.h[2] \n" "fmla v31.8h, %8.8h, v0.h[3] \n" "fmla v28.8h, %9.8h, v0.h[1] \n" "fmla v29.8h, %9.8h, v0.h[2] \n" "fmla v30.8h, %9.8h, v0.h[3] \n" "fmla v31.8h, %9.8h, v0.h[4] \n" "fmla v28.8h, %10.8h, v0.h[2] \n" "fmla v29.8h, %10.8h, v0.h[3] \n" "fmla v30.8h, %10.8h, v0.h[4] \n" "fmla v31.8h, %10.8h, v0.h[5] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v1.8h}, [%2] \n" // r1 "fmla v28.8h, %11.8h, v1.h[0] \n" "fmla v29.8h, %11.8h, v1.h[1] \n" "fmla v30.8h, %11.8h, v1.h[2] \n" "fmla v31.8h, %11.8h, v1.h[3] \n" "fmla v28.8h, %12.8h, v1.h[1] \n" "fmla v29.8h, %12.8h, v1.h[2] \n" "fmla v30.8h, %12.8h, v1.h[3] \n" "fmla v31.8h, %12.8h, v1.h[4] \n" "fmla v28.8h, %13.8h, v1.h[2] \n" "fmla v29.8h, %13.8h, v1.h[3] \n" "fmla v30.8h, %13.8h, v1.h[4] \n" "fmla v31.8h, %13.8h, v1.h[5] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v2.8h}, [%3] \n" // r2 "fmla v28.8h, %14.8h, v2.h[0] \n" "fmla v29.8h, %14.8h, v2.h[1] \n" "fmla v30.8h, %14.8h, v2.h[2] \n" "fmla v31.8h, %14.8h, v2.h[3] \n" "fmla v28.8h, %15.8h, v2.h[1] \n" "fmla v29.8h, %15.8h, v2.h[2] \n" "fmla v30.8h, %15.8h, v2.h[3] \n" "fmla v31.8h, %15.8h, v2.h[4] \n" "fmla v28.8h, %16.8h, v2.h[2] \n" "fmla v29.8h, %16.8h, v2.h[3] \n" "fmla v30.8h, %16.8h, v2.h[4] \n" "fmla v31.8h, %16.8h, v2.h[5] \n" "add %1, %1, #8 \n" "add %2, %2, #8 \n" "add %3, %3, #8 \n" "st1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v28", "v29", "v30", "v31"); } for (; j + 1 < outw; j += 2) { asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v30.8h, v31.8h}, [%0] \n" // sum0 sum1 "prfm pldl1keep, [%1, #64] \n" "ld1 {v0.4h}, [%1] \n" // r0 "fmla v30.8h, %8.8h, v0.h[0] \n" "fmla v31.8h, %8.8h, v0.h[1] \n" "fmla v30.8h, %9.8h, v0.h[1] \n" "fmla v31.8h, %9.8h, v0.h[2] \n" "fmla v30.8h, %10.8h, v0.h[2] \n" "fmla v31.8h, %10.8h, v0.h[3] \n" "prfm pldl1keep, [%2, #64] \n" "ld1 {v1.4h}, [%2] \n" // r1 "fmla v30.8h, %11.8h, v1.h[0] \n" "fmla v31.8h, %11.8h, v1.h[1] \n" "fmla v30.8h, %12.8h, v1.h[1] \n" "fmla v31.8h, %12.8h, v1.h[2] \n" "fmla v30.8h, %13.8h, v1.h[2] \n" "fmla v31.8h, %13.8h, v1.h[3] \n" "prfm pldl1keep, [%3, #64] \n" "ld1 {v2.4h}, [%3] \n" // r2 "fmla v30.8h, %14.8h, v2.h[0] \n" "fmla v31.8h, %14.8h, v2.h[1] \n" "fmla v30.8h, %15.8h, v2.h[1] \n" "fmla v31.8h, %15.8h, v2.h[2] \n" "fmla v30.8h, %16.8h, v2.h[2] \n" "fmla v31.8h, %16.8h, v2.h[3] \n" "add %1, %1, #4 \n" "add %2, %2, #4 \n" "add %3, %3, #4 \n" "st1 {v30.8h, v31.8h}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v30", "v31"); } for (; j < outw; j++) { asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v30.8h}, [%0] \n" // sum0 "prfm pldl1keep, [%1, #64] \n" "ld1 {v0.4h}, [%1] \n" // r0 "fmla v30.8h, %8.8h, v0.h[0] \n" "fmla v30.8h, %9.8h, v0.h[1] \n" "fmla v30.8h, %10.8h, v0.h[2] \n" "prfm pldl1keep, [%2, #64] \n" "ld1 {v1.4h}, [%2] \n" // r1 "fmla v30.8h, %11.8h, v1.h[0] \n" "fmla v30.8h, %12.8h, v1.h[1] \n" "fmla v30.8h, %13.8h, v1.h[2] \n" "prfm pldl1keep, [%3, #64] \n" "ld1 {v2.4h}, [%3] \n" // r2 "fmla v30.8h, %14.8h, v2.h[0] \n" "fmla v30.8h, %15.8h, v2.h[1] \n" "fmla v30.8h, %16.8h, v2.h[2] \n" "add %1, %1, #2 \n" "add %2, %2, #2 \n" "add %3, %3, #2 \n" "st1 {v30.8h}, [%0], #16 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v30"); } r0 += 2; r1 += 2; r2 += 2; } k0 += 9 * 8; } } } static void conv3x3s2_pack1to8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); float16x8_t _bias0 = bias ? vld1q_f16(bias + p * 8) : vdupq_n_f16((__fp16)0.f); out0.fill(_bias0); const __fp16* k0 = kernel.channel(p); int q = 0; for (; q < inch; q++) { __fp16* outptr0 = out0; const Mat img0 = bottom_blob.channel(q); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); float16x8_t _k00 = vld1q_f16(k0); float16x8_t _k01 = vld1q_f16(k0 + 8); float16x8_t _k02 = vld1q_f16(k0 + 16); float16x8_t _k10 = vld1q_f16(k0 + 24); float16x8_t _k11 = vld1q_f16(k0 + 32); float16x8_t _k12 = vld1q_f16(k0 + 40); float16x8_t _k20 = vld1q_f16(k0 + 48); float16x8_t _k21 = vld1q_f16(k0 + 56); float16x8_t _k22 = vld1q_f16(k0 + 64); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%0] \n" // sum0 sum1 sum2 sum3 "prfm pldl1keep, [%1, #128] \n" "ld1 {v0.8h}, [%1], #16 \n" // r0 "ld1 {v1.h}[0], [%1] \n" "fmla v28.8h, %8.8h, v0.h[0] \n" "fmla v29.8h, %8.8h, v0.h[2] \n" "fmla v30.8h, %8.8h, v0.h[4] \n" "fmla v31.8h, %8.8h, v0.h[6] \n" "fmla v28.8h, %9.8h, v0.h[1] \n" "fmla v29.8h, %9.8h, v0.h[3] \n" "fmla v30.8h, %9.8h, v0.h[5] \n" "fmla v31.8h, %9.8h, v0.h[7] \n" "fmla v28.8h, %10.8h, v0.h[2] \n" "fmla v29.8h, %10.8h, v0.h[4] \n" "fmla v30.8h, %10.8h, v0.h[6] \n" "fmla v31.8h, %10.8h, v1.h[0] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v2.8h}, [%2], #16 \n" // r1 "ld1 {v3.h}[0], [%2] \n" "fmla v28.8h, %11.8h, v2.h[0] \n" "fmla v29.8h, %11.8h, v2.h[2] \n" "fmla v30.8h, %11.8h, v2.h[4] \n" "fmla v31.8h, %11.8h, v2.h[6] \n" "fmla v28.8h, %12.8h, v2.h[1] \n" "fmla v29.8h, %12.8h, v2.h[3] \n" "fmla v30.8h, %12.8h, v2.h[5] \n" "fmla v31.8h, %12.8h, v2.h[7] \n" "fmla v28.8h, %13.8h, v2.h[2] \n" "fmla v29.8h, %13.8h, v2.h[4] \n" "fmla v30.8h, %13.8h, v2.h[6] \n" "fmla v31.8h, %13.8h, v3.h[0] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v4.8h}, [%3], #16 \n" // r2 "ld1 {v5.h}[0], [%3] \n" "fmla v28.8h, %14.8h, v4.h[0] \n" "fmla v29.8h, %14.8h, v4.h[2] \n" "fmla v30.8h, %14.8h, v4.h[4] \n" "fmla v31.8h, %14.8h, v4.h[6] \n" "fmla v28.8h, %15.8h, v4.h[1] \n" "fmla v29.8h, %15.8h, v4.h[3] \n" "fmla v30.8h, %15.8h, v4.h[5] \n" "fmla v31.8h, %15.8h, v4.h[7] \n" "fmla v28.8h, %16.8h, v4.h[2] \n" "fmla v29.8h, %16.8h, v4.h[4] \n" "fmla v30.8h, %16.8h, v4.h[6] \n" "fmla v31.8h, %16.8h, v5.h[0] \n" "st1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v28", "v29", "v30", "v31"); } for (; j + 1 < outw; j += 2) { asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v30.8h, v31.8h}, [%0] \n" // sum0 sum1 "prfm pldl1keep, [%1, #64] \n" "ld1 {v0.4h}, [%1], #8 \n" // r0 "ld1 {v1.h}[0], [%1] \n" "fmla v30.8h, %8.8h, v0.h[0] \n" "fmla v31.8h, %8.8h, v0.h[2] \n" "fmla v30.8h, %9.8h, v0.h[1] \n" "fmla v31.8h, %9.8h, v0.h[3] \n" "fmla v30.8h, %10.8h, v0.h[2] \n" "fmla v31.8h, %10.8h, v1.h[0] \n" "prfm pldl1keep, [%2, #64] \n" "ld1 {v2.4h}, [%2], #8 \n" // r1 "ld1 {v3.h}[0], [%2] \n" "fmla v30.8h, %11.8h, v2.h[0] \n" "fmla v31.8h, %11.8h, v2.h[2] \n" "fmla v30.8h, %12.8h, v2.h[1] \n" "fmla v31.8h, %12.8h, v2.h[3] \n" "fmla v30.8h, %13.8h, v2.h[2] \n" "fmla v31.8h, %13.8h, v3.h[0] \n" "prfm pldl1keep, [%3, #64] \n" "ld1 {v4.4h}, [%3], #8 \n" // r2 "ld1 {v5.h}[0], [%3] \n" "fmla v30.8h, %14.8h, v4.h[0] \n" "fmla v31.8h, %14.8h, v4.h[2] \n" "fmla v30.8h, %15.8h, v4.h[1] \n" "fmla v31.8h, %15.8h, v4.h[3] \n" "fmla v30.8h, %16.8h, v4.h[2] \n" "fmla v31.8h, %16.8h, v5.h[0] \n" "st1 {v30.8h, v31.8h}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v30", "v31"); } for (; j < outw; j++) { asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v30.8h}, [%0] \n" // sum0 "prfm pldl1keep, [%1, #64] \n" "ld1 {v0.4h}, [%1] \n" // r0 "fmla v30.8h, %8.8h, v0.h[0] \n" "fmla v30.8h, %9.8h, v0.h[1] \n" "fmla v30.8h, %10.8h, v0.h[2] \n" "prfm pldl1keep, [%2, #64] \n" "ld1 {v1.4h}, [%2] \n" // r1 "fmla v30.8h, %11.8h, v1.h[0] \n" "fmla v30.8h, %12.8h, v1.h[1] \n" "fmla v30.8h, %13.8h, v1.h[2] \n" "prfm pldl1keep, [%3, #64] \n" "ld1 {v2.4h}, [%3] \n" // r2 "fmla v30.8h, %14.8h, v2.h[0] \n" "fmla v30.8h, %15.8h, v2.h[1] \n" "fmla v30.8h, %16.8h, v2.h[2] \n" "add %1, %1, #4 \n" "add %2, %2, #4 \n" "add %3, %3, #4 \n" "st1 {v30.8h}, [%0], #16 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2) // %3 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "w"(_k00), // %8 "w"(_k01), // %9 "w"(_k02), // %10 "w"(_k10), // %11 "w"(_k11), // %12 "w"(_k12), // %13 "w"(_k20), // %14 "w"(_k21), // %15 "w"(_k22) // %16 : "cc", "memory", "v0", "v1", "v2", "v30"); } r0 += tailstep; r1 += tailstep; r2 += tailstep; } k0 += 9 * 8; } } }
flexSuperpixelOperator.h
#ifndef flexSuperpixelOperator_H #define flexSuperpixelOperator_H #include <vector> #include "flexLinearOperator.h" //! represents a superpixel operator /*! downsamples data of size upsamplingFactor * targetDimension size to targetDimension */ template<typename T> class flexSuperpixelOperator : public flexLinearOperator<T> { #ifdef __CUDACC__ typedef thrust::device_vector<T> Tdata; #else typedef std::vector<T> Tdata; #endif private: std::vector<int> targetDimension; T upsamplingFactor; public: //! initializes the superpixel operator. Downsamples image of size aUpsamplingFactor * aTargetDimension to size aTargetDimension /*! \param aTargetDimension target dimension of downsampled image \param aUpsamplingFactor aUpsamplingFactor * aTargetDimension is original image size \param aMinus determines if operator is negated \sa isMinus */ flexSuperpixelOperator(std::vector<int> aTargetDimension, T aUpsamplingFactor, bool aMinus) : flexLinearOperator<T>((int)(vectorProduct(aTargetDimension)), (int)(vectorProduct(aTargetDimension)*aUpsamplingFactor*aUpsamplingFactor), superpixelOp, aMinus) { this->targetDimension.resize(aTargetDimension.size()); this->targetDimension = aTargetDimension; this->upsamplingFactor = aUpsamplingFactor; }; flexSuperpixelOperator<T>* copy() { return new flexSuperpixelOperator<T>(this->targetDimension, this->upsamplingFactor, this->isMinus); } //to implement void times(bool transposed, const Tdata &input, Tdata &output) { } void timesPlus(bool transposed, const Tdata &input, Tdata &output) { if (this->isMinus) { doTimes(transposed,input,output, MINUS); } else { doTimes(transposed,input,output, PLUS); } } void timesMinus(bool transposed, const Tdata &input, Tdata &output) { if (this->isMinus) { doTimes(transposed,input,output, PLUS); } else { doTimes(transposed,input,output, MINUS); } } std::vector<T> getAbsRowSum(bool transposed) { if (transposed) { return std::vector<T>(this->getNumCols(), (T)1 / (T)(this->upsamplingFactor*this->upsamplingFactor)); } else { return std::vector<T>(this->getNumRows(), (T)1); } } T getMaxRowSumAbs(bool transposed) { if (transposed) { return (T)1 / (T)(this->upsamplingFactor*this->upsamplingFactor); } else { return (T)1; } } #ifdef __CUDACC__ thrust::device_vector<T> getAbsRowSumCUDA(bool transposed) { Tdata result(this->getNumRows(),(T)1); return result; } #endif private: int indexI(int index, int sizeX) { return index % sizeX; } int indexJ(int index, int sizeX, int sizeY) { return (index / sizeX) % sizeY; } int index2DtoLinear(int i, int j, int sizeY) { return (i*sizeY + j); } void calcTimes(const Tdata &input, Tdata &output, mySign signRule) { T factor = (T)1 / (this->upsamplingFactor*this->upsamplingFactor); int iOuterEnd = targetDimension[0]; int jOuterEnd = targetDimension[1]; int sizeY = targetDimension[1] * (int)this->upsamplingFactor; #pragma omp parallel for for (int i = 0; i < iOuterEnd; ++i) { for (int j = 0; j < jOuterEnd; ++j) { //printf("Output: (%d,%d) : %d\n", i, j, index2DtoLinear(i, j, this->targetDimension[1])); int outputIndex = index2DtoLinear(i, j, targetDimension[1]); int iInnerStart = i*(int)this->upsamplingFactor; int iInnerEnd = (i + 1)*(int)this->upsamplingFactor; int jInnerStart = j*(int)this->upsamplingFactor; int jInnerEnd = (j + 1)*(int)this->upsamplingFactor; T tmpResult = (T)0; for (int iInner = iInnerStart; iInner < iInnerEnd; ++iInner) { for (int jInner = jInnerStart; jInner < jInnerEnd; ++jInner) { int inputIndex = index2DtoLinear(iInner, jInner, sizeY); tmpResult += input[inputIndex]; /*printf("Inner: (%d,%d) : %d\n", iInner, jInner, inputIndex); int innerJ = indexI(inputIndex, this->targetDimension[0] * this->upsamplingFactor); int innerI = indexJ(inputIndex, this->targetDimension[0] * this->upsamplingFactor, this->targetDimension[1] * this->upsamplingFactor); printf("Back: (%d,%d) \n", innerI, innerJ); int backI = innerI / this->upsamplingFactor; int backJ = innerJ / this->upsamplingFactor; printf("BackInner: (%d,%d) \n", backI, backJ); if (backI != i || backJ != j) { mexErrMsgTxt("PROBLEM!!!\n"); }*/ } } switch (signRule) { case PLUS: { output[outputIndex] += factor*tmpResult; break; } case MINUS: { output[outputIndex] -= factor*tmpResult; break; } case EQUALS: { output[outputIndex] = factor*tmpResult; break; } } } } } void calcTimesTransposed(const Tdata &input, Tdata &output, mySign signRule) { T factor = (T)1 / (this->upsamplingFactor*this->upsamplingFactor); int sizeX = targetDimension[0] * (int)this->upsamplingFactor; int sizeY = targetDimension[1] * (int)this->upsamplingFactor; #pragma omp parallel for for (int i = 0; i < sizeX; ++i) { for (int j = 0; j < sizeY; ++j) { int inputIndex = index2DtoLinear(i, j, sizeY); //int innerJ = indexI(inputIndex, this->targetDimension[0] * this->upsamplingFactor); //int innerI = indexJ(inputIndex, this->targetDimension[0] * this->upsamplingFactor, this->targetDimension[1] * this->upsamplingFactor); //printf("Back: (%d,%d) \n", innerI, innerJ); int backI = i / (int)this->upsamplingFactor; int backJ = j / (int)this->upsamplingFactor; int outputIndex = index2DtoLinear(backI, backJ, targetDimension[1]); //printf("Back: (%d,%d) %d,%d \n", backI, backJ, inputIndex, outputIndex); switch (signRule) { case PLUS: { output[inputIndex] += factor*input[outputIndex]; break; } case MINUS: { output[inputIndex] -= factor*input[outputIndex]; break; } case EQUALS: { output[inputIndex] = factor*input[outputIndex]; break; } } } } } void doTimes(bool transposed, const Tdata &input, Tdata &output, mySign signRule) { if (transposed) { calcTimesTransposed(input, output, signRule); } else { calcTimes(input, output, signRule); } } }; #endif
pr91987.c
/* PR c++/91987 */ int bar (void); void baz (int *); #pragma omp declare target to (baz) void foo (int *a, int (*b)[10][10]) { #pragma omp target map(a[bar ()]) baz (a); #pragma omp target map(a[bar ():1]) baz (a); #pragma omp target map(a[10:bar ()]) baz (a); #pragma omp task depend(inout:a[10:bar ()]) baz (a); #pragma omp task depend(inout:a[10:bar ()]) baz (a); #pragma omp parallel reduction(+:a[bar ():2]) baz (a); #pragma omp parallel reduction(+:a[2:bar ()]) baz (a); #pragma omp parallel reduction(+:b[bar ():2][bar ():10][bar ():10]) baz (a); }
GB_unop__asinh_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__asinh_fp32_fp32) // op(A') function: GB (_unop_tran__asinh_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = asinhf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = asinhf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = asinhf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ASINH || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__asinh_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = asinhf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = asinhf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__asinh_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
i3lock-fancy-rapid.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <unistd.h> #include <sys/wait.h> #include <sys/shm.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/extensions/XShm.h> #include <omp.h> void box_blur_h(uint32_t *dest, uint32_t *src, int height, int width, int radius) { double coeff = 1.0 / (radius * 2 + 1); #pragma omp parallel for for (int i = 0; i < height; ++i) { int iwidth = i * width; double r_acc = 0.0; double g_acc = 0.0; double b_acc = 0.0; for (int j = -radius; j < width; ++j) { if (j - radius - 1 >= 0) { int index = iwidth + j - radius - 1; r_acc -= coeff * ((src[index] & 0xff0000) >> 16); g_acc -= coeff * ((src[index] & 0x00ff00) >> 8); b_acc -= coeff * ((src[index] & 0x0000ff)); } if (j + radius < width) { int index = iwidth + j + radius; r_acc += coeff * ((src[index] & 0xff0000) >> 16); g_acc += coeff * ((src[index] & 0x00ff00) >> 8); b_acc += coeff * ((src[index] & 0x0000ff)); } if (j < 0) continue; int index = iwidth + j; dest[index] = 0 | (((uint32_t)(r_acc + 0.5) & 0xff) << 16) | (((uint32_t)(g_acc + 0.5) & 0xff) << 8) | (((uint32_t)(b_acc + 0.5) & 0xff)); } } } void box_blur_v(uint32_t *dest, uint32_t *src, int height, int width, int radius) { double coeff = 1.0 / (radius * 2 + 1); #pragma omp parallel for for (int j = 0; j < width; ++j) { double r_acc = 0.0; double g_acc = 0.0; double b_acc = 0.0; for (int i = -radius; i < height; ++i) { if (i - radius - 1 >= 0) { int index = (i - radius - 1) * width + j; r_acc -= coeff * ((src[index] & 0xff0000) >> 16); g_acc -= coeff * ((src[index] & 0x00ff00) >> 8); b_acc -= coeff * ((src[index] & 0x0000ff)); } if (i + radius < height) { int index = (i + radius) * width + j; r_acc += coeff * ((src[index] & 0xff0000) >> 16); g_acc += coeff * ((src[index] & 0x00ff00) >> 8); b_acc += coeff * ((src[index] & 0x0000ff)); } if (i < 0) continue; int index = i * width + j; dest[index] = 0 | (((uint32_t)(r_acc + 0.5) & 0xff) << 16) | (((uint32_t)(g_acc + 0.5) & 0xff) << 8) | (((uint32_t)(b_acc + 0.5) & 0xff)); } } } void box_blur_once(uint32_t *dest, uint32_t *src, uint32_t *scratch, int height, int width, int radius) { box_blur_h(scratch, src, height, width, radius); box_blur_v(dest, scratch, height, width, radius); } void box_blur(uint32_t *dest, uint32_t *src, int height, int width, int radius, int times) { uint32_t *origdest = dest; uint32_t *scratch = malloc(width * height * sizeof(*scratch)); box_blur_once(dest, src, scratch, height, width, radius); for (int i = 0; i < times - 1; ++i) { uint32_t *tmp = src; src = dest; dest = tmp; box_blur_once(dest, src, scratch, height, width, radius); } free(scratch); // We're flipping between using dest and src; // if the last buffer we used was src, copy that over to dest. if (dest != origdest) memcpy(origdest, dest, width * height * sizeof(*dest)); } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "usage: %s radius times [OPTIONS]\n", argv[0]); exit(EXIT_FAILURE); } Display *display = XOpenDisplay(NULL); Window root = XDefaultRootWindow(display); XWindowAttributes gwa; XGetWindowAttributes(display, root, &gwa); int height = gwa.height / SCALE; int width = gwa.width / SCALE; uint32_t *preblur = malloc(height * width * sizeof(*preblur)); // Create shm image XShmSegmentInfo shminfo; XImage *image = XShmCreateImage( display, DefaultVisual(display, DefaultScreen(display)), 32, ZPixmap, NULL, &shminfo, gwa.width, gwa.height); // Attach shm image shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT|0777); shminfo.shmaddr = image->data = shmat(shminfo.shmid, 0, 0); shminfo.readOnly = False; XShmAttach(display, &shminfo); if (!XShmGetImage(display, root, image, 0, 0, AllPlanes)) { fprintf(stderr, "Failed to get image.\n"); exit(EXIT_FAILURE); } #pragma omp parallel for for (int i = 0; i < height; ++i) { int iwidth = i * width; for (int j = 0; j < width; ++j) { int index = iwidth + j; unsigned long pixel = XGetPixel(image, j * SCALE, i * SCALE); preblur[index] = pixel & 0x00ffffff; } } XShmDetach(display, &shminfo); XDestroyImage(image); XDestroyWindow(display, root); XCloseDisplay(display); uint32_t *postblur = malloc(height * width * sizeof(*postblur)); box_blur(postblur, preblur, height, width, atoi(argv[1]), atoi(argv[2])); free(preblur); // Upscale uint32_t *upscaled; if (SCALE == 1) { upscaled = postblur; } else { upscaled = malloc(height * SCALE * width * SCALE * sizeof(*upscaled)); #pragma omp parallel for for (int i = 0; i < height * SCALE; ++i) { for (int j = 0; j < width * SCALE; ++j) { upscaled[i * width * SCALE + j] = postblur[(i / SCALE) * width + (j / SCALE)]; } } } int fds[2]; pipe(fds); if (fork()) { write(fds[1], upscaled, height * SCALE * width * SCALE * sizeof(*upscaled)); int status; wait(&status); exit(WEXITSTATUS(status)); } else { dup2(fds[0], STDIN_FILENO); char geometry[32]; snprintf(geometry, sizeof(geometry), "%ix%i:native", width * SCALE, height * SCALE); int argskip = 3; char *new_argv[6 + (argc - argskip)]; new_argv[0] = "i3lock"; new_argv[1] = "--image"; new_argv[2] = "/dev/stdin"; new_argv[3] = "--raw"; new_argv[4] = geometry; int idx = 5; for (int i = 0; i < argc - argskip; ++i) new_argv[idx++] = argv[i + argskip]; new_argv[idx++] = NULL; execvp(new_argv[0], new_argv); exit(EXIT_FAILURE); } }
GB_unaryop__abs_uint32_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__abs_uint32_int16 // op(A') function: GB_tran__abs_uint32_int16 // C type: uint32_t // A type: int16_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint32_t z = (uint32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT32 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint32_int16 ( uint32_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__abs_uint32_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
explicit_task_thread_num.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> __attribute__ ((noinline)) // workaround for bug in icc void print_task_info_at(int ancestor_level, int id) { #pragma omp critical { int task_type; char buffer[2048]; ompt_data_t *parallel_data; ompt_data_t *task_data; int thread_num; ompt_get_task_info(ancestor_level, &task_type, &task_data, NULL, &parallel_data, &thread_num); format_task_type(task_type, buffer); printf("%" PRIu64 ": ancestor_level=%d id=%d task_type=%s=%d " "parallel_id=%" PRIu64 " task_id=%" PRIu64 " thread_num=%d\n", ompt_get_thread_data()->value, ancestor_level, id, buffer, task_type, parallel_data->value, task_data->value, thread_num); } }; int main() { #pragma omp parallel num_threads(2) { if (omp_get_thread_num() == 1) { // To assert that task is executed by the worker thread, // if(0) is used in order to ensure that the task is immediately // executed after its creation. #pragma omp task if(0) { // thread_num should be equal to 1 for both explicit and implicit task print_task_info_at(0, 1); print_task_info_at(1, 0); }; } } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_event_parallel_begin' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task' // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_initial_task_begin // parallel region used only to determine worker thread id // CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin // CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin // CHECK-DAG: {{^}}[[WORKER_ID:[0-9]+]]: ompt_event_implicit_task_begin // thread_num must be equal to 1 for both explicit and the implicit tasks // CHECK: {{^}}[[WORKER_ID]]: ancestor_level=0 id=1 task_type=ompt_task_explicit // CHECK-SAME: thread_num=1 // CHECK: {{^}}[[WORKER_ID]]: ancestor_level=1 id=0 task_type=ompt_task_implicit // CHECK-SAME: thread_num=1 return 0; }
schelude-clause-guide.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main(int argc, char **argv) { int i, n=16,chunk,a[n],suma=0; if(argc < 2) { fprintf(stderr,"\nFalta iteraciones y/o chunk \n"); exit(-1); } //n = atoi(argv[1]); if (n>20) n=20; chunk = atoi(argv[1]); for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for firstprivate(suma) \ lastprivate(suma) schedule(guided,chunk) for (i=0; i<n; i++) { suma = suma + a[i]; printf(" thread %d suma a[%d]=%d suma=%d \n", omp_get_thread_num(),i,a[i],suma); } printf("Fuera de 'parallel for' suma=%d\n",suma); }
ast-dump-openmp-distribute.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 for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp distribute for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp distribute 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 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 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.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: | `-OMPDistributeDirective {{.*}} <line:4:1, col:23> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // 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> openmp_structured_block // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute.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:3> '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: | `-OMPDistributeDirective {{.*}} <line:10:1, col:23> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // 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> openmp_structured_block // 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.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:3> '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: | `-OMPDistributeDirective {{.*}} <line:17:1, col:35> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:24, col:34> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:33> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:33> 'int' 1 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // 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> openmp_structured_block // 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.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:3> '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: | `-OMPDistributeDirective {{.*}} <line:24:1, col:35> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:24, col:34> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:33> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:33> 'int' 2 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // 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> openmp_structured_block // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute.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:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:5> '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: `-OMPDistributeDirective {{.*}} <line:31:1, col:35> // CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:24, col:34> // CHECK-NEXT: | `-ConstantExpr {{.*}} <col:33> 'int' // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:33> 'int' 2 // CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // 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> openmp_structured_block // 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.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:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
grid.c
/* Copyright 2014-2015 The Regents of the University of California. * Copyright 2015-2019 Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * 2011-2019 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2014 Frank Ong <frankong@berkeley.edu> */ #include <math.h> #include <complex.h> #include <assert.h> #include <string.h> #include "num/multind.h" #include "num/flpmath.h" #include "num/specfun.h" #include "misc/nested.h" #include "misc/misc.h" #include "grid.h" static double kb(double beta, double x) { if (fabs(x) >= 0.5) return 0.; return bessel_i0(beta * sqrt(1. - pow(2. * x, 2.))) / bessel_i0(beta); } static void kb_precompute(double beta, int n, float table[n + 1]) { for (int i = 0; i < n + 1; i++) table[i] = kb(beta, (double)(i) / (double)(n - 1) / 2.); } static double ftkb(double beta, double x) { double a = sqrt(pow(beta, 2.) - pow(M_PI * x, 2.)); return ((0. == a) ? 1. : (a / sinh(a))); // * bessel_i0(beta); } static double rolloff(double x, double beta, double width) { return ftkb(beta, x * width) / ftkb(beta, 0.); } // Linear interpolation static float lerp(float a, float b, float c) { return (1. - c) * a + c * b; } // Linear interpolation look up static float intlookup(int n, const float table[n + 1], float x) { float fpart; // fpart = modff(x * n, &ipart); // int index = ipart; int index = (int)(x * (n - 1)); fpart = x * (n - 1) - (float)index; #if 1 assert(index >= 0); assert(index <= n); assert(fpart >= 0.); assert(fpart <= 1.); #endif float l = lerp(table[index], table[index + 1], fpart); #if 1 assert(l <= 1.); assert(0 >= 0.); #endif return l; } enum { kb_size = 100 }; static float kb_table[kb_size + 1]; static float kb_beta = -1.; void gridH(const struct grid_conf_s* conf, const complex float* traj, const long ksp_dims[4], complex float* dst, const long grid_dims[4], const complex float* grid) { long C = ksp_dims[3]; // precompute kaiser bessel table #pragma omp critical if (-1 == kb_beta) { kb_precompute(conf->beta, kb_size, kb_table); kb_beta = conf->beta; } assert(fabs(kb_beta - conf->beta) < 1.E-6); assert(1 == ksp_dims[0]); long samples = ksp_dims[1] * ksp_dims[2]; #pragma omp parallel for for(int i = 0; i < samples; i++) { float pos[3]; pos[0] = conf->os * (creal(traj[i * 3 + 0])); pos[1] = conf->os * (creal(traj[i * 3 + 1])); pos[2] = conf->os * (creal(traj[i * 3 + 2])); pos[0] += (grid_dims[0] > 1) ? ((float)grid_dims[0] / 2.) : 0.; pos[1] += (grid_dims[1] > 1) ? ((float)grid_dims[1] / 2.) : 0.; pos[2] += (grid_dims[2] > 1) ? ((float)grid_dims[2] / 2.) : 0.; complex float val[C]; for (int j = 0; j < C; j++) val[j] = 0.0; grid_pointH(C, 3, grid_dims, pos, val, grid, conf->periodic, conf->width, kb_size, kb_table); for (int j = 0; j < C; j++) dst[j * samples + i] += val[j]; } } void grid(const struct grid_conf_s* conf, const complex float* traj, const long grid_dims[4], complex float* grid, const long ksp_dims[4], const complex float* src) { long C = ksp_dims[3]; // precompute kaiser bessel table #pragma omp critical if (-1 == kb_beta) { kb_precompute(conf->beta, kb_size, kb_table); kb_beta = conf->beta; } assert(fabs(kb_beta - conf->beta) < 1.E-6); assert(1 == ksp_dims[0]); long samples = ksp_dims[1] * ksp_dims[2]; // grid #pragma omp parallel for for(int i = 0; i < samples; i++) { float pos[3]; pos[0] = conf->os * (creal(traj[i * 3 + 0])); pos[1] = conf->os * (creal(traj[i * 3 + 1])); pos[2] = conf->os * (creal(traj[i * 3 + 2])); pos[0] += (grid_dims[0] > 1) ? ((float) grid_dims[0] / 2.) : 0.; pos[1] += (grid_dims[1] > 1) ? ((float) grid_dims[1] / 2.) : 0.; pos[2] += (grid_dims[2] > 1) ? ((float) grid_dims[2] / 2.) : 0.; complex float val[C]; for (int j = 0; j < C; j++) val[j] = src[j * samples + i]; grid_point(C, 3, grid_dims, pos, grid, val, conf->periodic, conf->width, kb_size, kb_table); } } static void grid2_dims(unsigned int D, const long trj_dims[D], const long ksp_dims[D], const long grid_dims[D]) { assert(D >= 4); assert(md_check_compat(D - 3, ~0, grid_dims + 3, ksp_dims + 3)); // assert(md_check_compat(D - 3, ~(MD_BIT(0) | MD_BIT(1)), trj_dims + 3, ksp_dims + 3)); assert(md_check_bounds(D - 3, ~0, trj_dims + 3, ksp_dims + 3)); assert(3 == trj_dims[0]); assert(1 == trj_dims[3]); assert(1 == ksp_dims[0]); } void grid2(const struct grid_conf_s* conf, unsigned int D, const long trj_dims[D], const complex float* traj, const long grid_dims[D], complex float* dst, const long ksp_dims[D], const complex float* src) { grid2_dims(D, trj_dims, ksp_dims, grid_dims); long ksp_strs[D]; md_calc_strides(D, ksp_strs, ksp_dims, CFL_SIZE); long trj_strs[D]; md_calc_strides(D, trj_strs, trj_dims, CFL_SIZE); long grid_strs[D]; md_calc_strides(D, grid_strs, grid_dims, CFL_SIZE); long pos[D]; for (unsigned int i = 0; i < D; i++) pos[i] = 0; do { grid(conf, &MD_ACCESS(D, trj_strs, pos, traj), grid_dims, &MD_ACCESS(D, grid_strs, pos, dst), ksp_dims, &MD_ACCESS(D, ksp_strs, pos, src)); } while(md_next(D, ksp_dims, (~0 ^ 15), pos)); } void grid2H(const struct grid_conf_s* conf, unsigned int D, const long trj_dims[D], const complex float* traj, const long ksp_dims[D], complex float* dst, const long grid_dims[D], const complex float* src) { grid2_dims(D, trj_dims, ksp_dims, grid_dims); long ksp_strs[D]; md_calc_strides(D, ksp_strs, ksp_dims, CFL_SIZE); long trj_strs[D]; md_calc_strides(D, trj_strs, trj_dims, CFL_SIZE); long grid_strs[D]; md_calc_strides(D, grid_strs, grid_dims, CFL_SIZE); long pos[D]; for (unsigned int i = 0; i < D; i++) pos[i] = 0; do { gridH(conf, &MD_ACCESS(D, trj_strs, pos, traj), ksp_dims, &MD_ACCESS(D, ksp_strs, pos, dst), grid_dims, &MD_ACCESS(D, grid_strs, pos, src)); } while(md_next(D, ksp_dims, (~0 ^ 15), pos)); } typedef void CLOSURE_TYPE(grid_update_t)(int ind, float d); #ifndef __clang__ #define VLA(x) x #else // blocks extension does not play well even with arguments which // just look like variably-modified types #define VLA(x) #endif static void grid_point_gen(int N, const long dims[VLA(N)], const float pos[VLA(N)], bool periodic, float width, int kb_size, const float kb_table[VLA(kb_size + 1)], grid_update_t update) { #ifndef __clang__ int sti[N]; int eni[N]; int off[N]; #else // blocks extension does not play well with variably-modified types int* sti = alloca(sizeof(int[N])); int* eni = alloca(sizeof(int[N])); int* off = alloca(sizeof(int[N])); #endif for (int j = 0; j < N; j++) { sti[j] = (int)ceil(pos[j] - width); eni[j] = (int)floor(pos[j] + width); off[j] = 0; if (sti[j] > eni[j]) return; if (!periodic) { sti[j] = MAX(sti[j], 0); eni[j] = MIN(eni[j], dims[j] - 1); } else { while (sti[j] + off[j] < 0) off[j] += dims[j]; } if (1 == dims[j]) { assert(0. == pos[j]); // ==0. fails nondeterministically for test_nufft_forward bbdec08cb sti[j] = 0; eni[j] = 0; } } __block NESTED(void, grid_point_r, (int N, int ind, float d)) // __block for recursion { if (0 == N) { NESTED_CALL(update, (ind, d)); } else { N--; for (int w = sti[N]; w <= eni[N]; w++) { float frac = fabs(((float)w - pos[N])); float d2 = d * intlookup(kb_size, kb_table, frac / width); int ind2 = (ind * dims[N] + ((w + off[N]) % dims[N])); grid_point_r(N, ind2, d2); } } }; grid_point_r(N, 0, 1.); } void grid_point(unsigned int ch, int N, const long dims[VLA(N)], const float pos[VLA(N)], complex float* dst, const complex float val[VLA(ch)], bool periodic, float width, int kb_size, const float kb_table[kb_size + 1]) { NESTED(void, update, (int ind, float d)) { for (unsigned int c = 0; c < ch; c++) { // we are allowed to update real and imaginary part independently which works atomically #pragma omp atomic __real(dst[ind + c * dims[0] * dims[1] * dims[2]]) += __real(val[c]) * d; #pragma omp atomic __imag(dst[ind + c * dims[0] * dims[1] * dims[2]]) += __imag(val[c]) * d; } }; grid_point_gen(N, dims, pos, periodic, width, kb_size, kb_table, update); } void grid_pointH(unsigned int ch, int N, const long dims[VLA(N)], const float pos[VLA(N)], complex float val[VLA(ch)], const complex float* src, bool periodic, float width, int kb_size, const float kb_table[kb_size + 1]) { NESTED(void, update, (int ind, float d)) { for (unsigned int c = 0; c < ch; c++) { // we are allowed to update real and imaginary part independently which works atomically #pragma omp atomic __real(val[c]) += __real(src[ind + c * dims[0] * dims[1] * dims[2]]) * d; #pragma omp atomic __imag(val[c]) += __imag(src[ind + c * dims[0] * dims[1] * dims[2]]) * d; } }; grid_point_gen(N, dims, pos, periodic, width, kb_size, kb_table, update); } double calc_beta(float os, float width) { return M_PI * sqrt(pow((width * 2. / os) * (os - 0.5), 2.) - 0.8); } static float pos(int d, int i) { return (1 == d) ? 0. : (((float)i - (float)d / 2.) / (float)d); } void rolloff_correction(float os, float width, float beta, const long dimensions[3], complex float* dst) { UNUSED(os); #pragma omp parallel for collapse(3) for (int z = 0; z < dimensions[2]; z++) for (int y = 0; y < dimensions[1]; y++) for (int x = 0; x < dimensions[0]; x++) dst[x + dimensions[0] * (y + z * dimensions[1])] = rolloff(pos(dimensions[0], x), beta, width) * rolloff(pos(dimensions[1], y), beta, width) * rolloff(pos(dimensions[2], z), beta, width); }
psd.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[257], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(Image *image) { switch (image->compose) { case ColorBurnCompositeOp: return(image->endian == LSBEndian ? "vidi" : "idiv"); case ColorDodgeCompositeOp: return(image->endian == LSBEndian ? " vid" : "div "); case ColorizeCompositeOp: return(image->endian == LSBEndian ? "rloc" : "colr"); case DarkenCompositeOp: return(image->endian == LSBEndian ? "krad" : "dark"); case DifferenceCompositeOp: return(image->endian == LSBEndian ? "ffid" : "diff"); case DissolveCompositeOp: return(image->endian == LSBEndian ? "ssid" : "diss"); case ExclusionCompositeOp: return(image->endian == LSBEndian ? "dums" : "smud"); case HardLightCompositeOp: return(image->endian == LSBEndian ? "tiLh" : "hLit"); case HardMixCompositeOp: return(image->endian == LSBEndian ? "xiMh" : "hMix"); case HueCompositeOp: return(image->endian == LSBEndian ? " euh" : "hue "); case LightenCompositeOp: return(image->endian == LSBEndian ? "etil" : "lite"); case LinearBurnCompositeOp: return(image->endian == LSBEndian ? "nrbl" : "lbrn"); case LinearDodgeCompositeOp: return(image->endian == LSBEndian ? "gddl" : "lddg"); case LinearLightCompositeOp: return(image->endian == LSBEndian ? "tiLl" : "lLit"); case LuminizeCompositeOp: return(image->endian == LSBEndian ? " mul" : "lum "); case MultiplyCompositeOp: return(image->endian == LSBEndian ? " lum" : "mul "); case OverlayCompositeOp: return(image->endian == LSBEndian ? "revo" : "over"); case PinLightCompositeOp: return(image->endian == LSBEndian ? "tiLp" : "pLit"); case SaturateCompositeOp: return(image->endian == LSBEndian ? " tas" : "sat "); case ScreenCompositeOp: return(image->endian == LSBEndian ? "nrcs" : "scrn"); case SoftLightCompositeOp: return(image->endian == LSBEndian ? "tiLs" : "sLit"); case VividLightCompositeOp: return(image->endian == LSBEndian ? "tiLv" : "vLit"); case OverCompositeOp: default: return(image->endian == LSBEndian ? "mron" : "norm"); } } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if ((image->alpha_trait != BlendPixelTrait) || (image->colorspace != sRGBColorspace)) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); if (image->alpha_trait != BlendPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->alpha_trait == UndefinedPixelTrait) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,0,0,MagickTrue,exception); if (complete_mask == (Image *) NULL) return(MagickFalse); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=(MagickRealType) background; (void) SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=(MagickRealType) GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=(char) layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(const Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); } if (image->depth > 16) return(4); if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static StringInfo *ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; ssize_t offset; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return((StringInfo *) NULL); profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); SetStringInfoName(profile,"8bim"); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) break; p=PushLongPixel(MSBEndian,p,&count); offset=(ssize_t) count; if (((p+offset) < blocks) || ((p+offset) > (blocks+length))) break; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ if (offset < 16) break; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((offset > 4) && (*(p+4) == 0)) *has_merged_image=MagickFalse; p+=offset; break; } default: { p+=offset; break; } } if ((offset & 0x01) != 0) p++; } return(profile); } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; if (type == 0) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); } color=image->colormap+(ssize_t) ConstrainColormapIndex(image, (ssize_t) GetPixelIndex(image,q),exception); if ((type == 0) && (channels > 1)) return; else color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case -3: case 1: { SetPixelGreen(image,pixel,q); break; } case -4: case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { unsigned short nibble; p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType) (QuantumRange*nibble)); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < (ssize_t) number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) { status=MagickFalse; break; } status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > (row_size+2048)) /* arbitrary number */ { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); if ((MagickSizeType) compact_size > GetBlobSize(image)) ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } if (ret == Z_STREAM_END) break; } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } /* else if (packet_size == 4) { TODO: Figure out what to do there. } */ else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { (void) SeekBlob(image,(MagickOffsetType) layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { (void) ResetImagePixels(mask,exception); (void) SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, (ssize_t) layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, (ssize_t) layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, (ssize_t) layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } (void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2, SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) (void) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (layer_info->mask.image != (Image *) NULL) layer_info->mask.image=DestroyImage(layer_info->mask.image); layer_info->mask.image=mask; } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); /* TODO: Remove this when we figure out how to support this */ if ((compression == ZipWithPrediction) && (image->depth == 32)) { (void) ThrowMagickException(exception,GetMagickModule(), TypeError,"CompressionNotSupported","ZipWithPrediction(32 bit)"); return(MagickFalse); } layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info, LayerInfo *layer_info) { int channel_type; register ssize_t i; if (layer_info->channels < psd_info->min_channels) return(MagickFalse); channel_type=RedChannel; if (psd_info->min_channels >= 3) channel_type|=(GreenChannel | BlueChannel); if (psd_info->min_channels >= 4) channel_type|=BlackChannel; for (i=0; i < (ssize_t) layer_info->channels; i++) { short type; type=layer_info->channel_info[i].type; if (type == -1) { channel_type|=AlphaChannel; continue; } if (type < -1) continue; if (type == 0) channel_type&=~RedChannel; else if (type == 1) channel_type&=~GreenChannel; else if (type == 2) channel_type&=~BlueChannel; else if (type == 3) channel_type&=~BlackChannel; } if (channel_type == 0) return(MagickTrue); if ((channel_type == AlphaChannel) && (layer_info->channels >= psd_info->min_channels + 1)) return(MagickTrue); return(MagickFalse); } static void AttachPSDLayers(Image *image,LayerInfo *layer_info, ssize_t number_layers) { register ssize_t i; ssize_t j; for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers == 0) { layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); return; } for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } static inline MagickBooleanType PSDSkipImage(const ImageInfo *image_info, const size_t index) { if (image_info->number_scenes == 0) return(MagickFalse); if (index < image_info->scene) return(MagickTrue); if (index > image_info->scene+image_info->number_scenes-1) return(MagickTrue); return(MagickFalse); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, index, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,(size_t) count); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,4); if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) || (LocaleNCompare(type,"Lr32",4) == 0))) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } if (size == 0) return(MagickTrue); layer_info=(LayerInfo *) NULL; number_layers=(ssize_t) ReadBlobSignedShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t top, left, bottom, right; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); top=(ssize_t) ReadBlobSignedLong(image); left=(ssize_t) ReadBlobSignedLong(image); bottom=(ssize_t) ReadBlobSignedLong(image); right=(ssize_t) ReadBlobSignedLong(image); if ((right < left) || (bottom < top)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].page.y=top; layer_info[i].page.x=left; layer_info[i].page.width=(size_t) (right-left); layer_info[i].page.height=(size_t) (bottom-top); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); if ((layer_info[i].channel_info[j].type < -4) || (layer_info[i].channel_info[j].type > 4)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"NoSuchImageChannel", image->filename); } layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); if (count != 4) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping != MagickFalse) { AttachPSDLayers(image,layer_info,number_layers); return(MagickTrue); } status=MagickTrue; index=0; for (i=0; i < number_layers; i++) { if ((layer_info[i].image == (Image *) NULL) || (PSDSkipImage(image_info,++index) != MagickFalse)) { for (j=0; j < (ssize_t) layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, (MagickSizeType) number_layers); if (status == MagickFalse) break; } if (status != MagickFalse) AttachPSDLayers(image,layer_info,number_layers); else layer_info=DestroyLayerInfo(layer_info,number_layers); return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; if ((image_info->number_scenes != 0) && (image_info->scene != 0)) return(MagickTrue); compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { ssize_t type; type=i; if ((type == 1) && (psd_info->channels == 2)) type=-1; if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,type,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t imageListLength; ssize_t count; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels < 1) ThrowReaderException(CorruptImageError,"MissingImageChannel"); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16) && (psd_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); psd_info.min_channels=3; if (psd_info.mode == LabMode) (void) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { psd_info.min_channels=4; (void) SetImageColorspace(image,CMYKColorspace,exception); } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { if (psd_info.depth != 32) { status=AcquireImageColormap(image,(size_t) (psd_info.depth < 16 ? 256 : 65536),exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); } psd_info.min_channels=1; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (psd_info.channels < psd_info.min_channels) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if ((psd_info.mode == IndexedMode) && (length < 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32)) { /* Duotone image data; the format of this data is undocumented. 32 bits per pixel; the colormap is ignored. */ (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=(size_t) length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; profile=(StringInfo *) NULL; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } profile=ParseImageResourceBlocks(image,blocks,(size_t) length, &has_merged_image,exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ (void) SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (EOFBlob(image) != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (image_info->ping != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); imageListLength=GetImageListLength(image); if ((has_merged_image != MagickFalse) || (imageListLength == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (imageListLength == 1) && (length != 0)) { (void) SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (imageListLength == 1) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } image->background_color.alpha=(MagickRealType) TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(image,exception); merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } if (profile != (StringInfo *) NULL) { Image *next; i=0; next=image; while (next != (Image *) NULL) { if (PSDSkipImage(image_info,i++) == MagickFalse) (void) SetImageProfile(next,GetStringInfoName(profile),profile, exception); next=next->next; } profile=DestroyStringInfo(profile); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned int) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=WriteBlobMSBLong(image,(unsigned int) size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobLong(image,(unsigned int) size)); return(WriteBlobLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); result=SetPSDSize(psd_info,image,size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const CompressionType compression, const ssize_t channels) { size_t length; ssize_t i, y; if (compression == RLECompression) { length=(size_t) WriteBlobShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) length=(size_t) WriteBlobShort(image,ZipWithoutPrediction); #endif else length=(size_t) WriteBlobShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { CompressionType compression; Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; compression=next_image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 : 3); if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression, (ssize_t) channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,compression, exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=(size_t) WriteBlobShort(image,(const unsigned short) channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) && ((ssize_t) length-(cnt+12)-(q-datum)) > 0) { (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) memmove(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); (void) SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size, ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; register ssize_t i; size_t layer_count, layer_index, length, name_length, rounded_size, size; status=MagickTrue; base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); (void) SetPSDSize(psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobShort(image,-(unsigned short) layer_count); else size+=WriteBlobShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0); } size+=WriteBlobSignedLong(image,(signed int) next_image->page.y); size+=WriteBlobSignedLong(image,(signed int) next_image->page.x); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+ next_image->rows)); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+ next_image->columns)); channels=1; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 : 3); total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(psd_info,image,-2); size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM"); size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,(const unsigned char) (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobLong(image,20); size+=WriteBlobSignedLong(image,(const signed int) mask->page.y); size+=WriteBlobSignedLong(image,(const signed int) mask->page.x); size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+ mask->page.y)); size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+ mask->page.x)); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,(const unsigned char) (mask->compose == NoCompositeOp ? 2 : 0)); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } /* Write the total size */ if (layers_size != (size_t*) NULL) *layers_size=size; if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) (void) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } return(status); } ModuleExport MagickBooleanType WritePSDLayers(Image * image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=WritePolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL, exception); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const StringInfo *icc_profile; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t length, num_channels, packet_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,exception) != MagickFalse)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } if (status != MagickFalse) { MagickOffsetType size_offset; size_t size; size_offset=TellBlob(image); (void) SetPSDSize(&psd_info,image,0); status=WritePSDLayersInternal(image,image_info,&psd_info,&size, exception); size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 12),size_offset); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (image_info->compression != UndefinedCompression) image->compression=image_info->compression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
interpolation_pl.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ #include <math.h> //------------------------------------------------------------------------------------------------------------------------------ static inline void InterpolateBlock_PL(level_type *level_f, int id_f, double prescale_f, level_type *level_c, int id_c, blockCopy_type *block){ // interpolate 3D array from read_i,j,k of read[] to write_i,j,k in write[] int write_dim_i = block->dim.i<<1; // calculate the dimensions of the resultant fine block int write_dim_j = block->dim.j<<1; int write_dim_k = block->dim.k<<1; int read_i = block->read.i; int read_j = block->read.j; int read_k = block->read.k; int read_jStride = block->read.jStride; int read_kStride = block->read.kStride; int write_i = block->write.i; int write_j = block->write.j; int write_k = block->write.k; int write_jStride = block->write.jStride; int write_kStride = block->write.kStride; double * __restrict__ read = block->read.ptr; double * __restrict__ write = block->write.ptr; if(block->read.box >=0){ read = level_c->my_boxes[ block->read.box].vectors[ id_c] + level_c->my_boxes[ block->read.box].ghosts*(1+level_c->my_boxes[ block->read.box].jStride+level_c->my_boxes[ block->read.box].kStride); read_jStride = level_c->my_boxes[block->read.box ].jStride; read_kStride = level_c->my_boxes[block->read.box ].kStride; } if(block->write.box>=0){ write = level_f->my_boxes[block->write.box].vectors[id_f] + level_f->my_boxes[block->write.box].ghosts*(1+level_f->my_boxes[block->write.box].jStride+level_f->my_boxes[block->write.box].kStride); write_jStride = level_f->my_boxes[block->write.box].jStride; write_kStride = level_f->my_boxes[block->write.box].kStride; } int i,j,k; for(k=0;k<write_dim_k;k++){ for(j=0;j<write_dim_j;j++){ for(i=0;i<write_dim_i;i++){ int write_ijk = ((i )+write_i) + (((j )+write_j)*write_jStride) + (((k )+write_k)*write_kStride); int read_ijk = ((i>>1)+ read_i) + (((j>>1)+ read_j)* read_jStride) + (((k>>1)+ read_k)* read_kStride); // // | o | o | // +---+---+---+---+ // | | x | x | | // // CAREFUL !!! you must guarantee you zero'd the MPI buffers(write[]) and destination boxes at some point to avoid 0.0*NaN or 0.0*inf // piecewise linear interpolation... NOTE, BC's must have been previously applied int delta_i= -1;if(i&0x1)delta_i= 1; // i.e. even points look backwards while odd points look forward int delta_j=-read_jStride;if(j&0x1)delta_j=read_jStride; int delta_k=-read_kStride;if(k&0x1)delta_k=read_kStride; write[write_ijk] = prescale_f*write[write_ijk] + 0.421875*read[read_ijk ] + 0.140625*read[read_ijk +delta_k] + 0.140625*read[read_ijk +delta_j ] + 0.046875*read[read_ijk +delta_j+delta_k] + 0.140625*read[read_ijk+delta_i ] + 0.046875*read[read_ijk+delta_i +delta_k] + 0.046875*read[read_ijk+delta_i+delta_j ] + 0.015625*read[read_ijk+delta_i+delta_j+delta_k]; }}} } //------------------------------------------------------------------------------------------------------------------------------ // perform a (inter-level) piecewise linear interpolation void interpolation_pl(level_type * level_f, int id_f, double prescale_f, level_type *level_c, int id_c){ exchange_boundary(level_c,id_c,0); apply_BCs_linear(level_c,id_c); uint64_t _timeCommunicationStart = CycleTime(); uint64_t _timeStart,_timeEnd; int buffer=0; int n; #ifdef USE_MPI // by convention, level_f allocates a combined array of requests for both level_f recvs and level_c sends... int nMessages = level_c->interpolation.num_sends + level_f->interpolation.num_recvs; MPI_Request *recv_requests = level_f->interpolation.requests; MPI_Request *send_requests = level_f->interpolation.requests + level_f->interpolation.num_recvs; // loop through packed list of MPI receives and prepost Irecv's... _timeStart = CycleTime(); #ifdef USE_MPI_THREAD_MULTIPLE #pragma omp parallel for schedule(dynamic,1) #endif for(n=0;n<level_f->interpolation.num_recvs;n++){ MPI_Irecv(level_f->interpolation.recv_buffers[n], level_f->interpolation.recv_sizes[n], MPI_DOUBLE, level_f->interpolation.recv_ranks[n], 7, // by convention, piecewise linear interpolation uses tag=7 MPI_COMM_WORLD, &recv_requests[n] ); } _timeEnd = CycleTime(); level_f->cycles.interpolation_recv += (_timeEnd-_timeStart); // pack MPI send buffers... _timeStart = CycleTime(); #pragma omp parallel for private(buffer) if(level_c->interpolation.num_blocks[0]>1) schedule(static,1) for(buffer=0;buffer<level_c->interpolation.num_blocks[0];buffer++){InterpolateBlock_PL(level_f,id_f,0.0,level_c,id_c,&level_c->interpolation.blocks[0][buffer]);} // !!! prescale==0 because you don't want to increment the MPI buffer _timeEnd = CycleTime(); level_f->cycles.interpolation_pack += (_timeEnd-_timeStart); // loop through MPI send buffers and post Isend's... _timeStart = CycleTime(); #ifdef USE_MPI_THREAD_MULTIPLE #pragma omp parallel for schedule(dynamic,1) #endif for(n=0;n<level_c->interpolation.num_sends;n++){ MPI_Isend(level_c->interpolation.send_buffers[n], level_c->interpolation.send_sizes[n], MPI_DOUBLE, level_c->interpolation.send_ranks[n], 7, // by convention, piecewise linear interpolation uses tag=7 MPI_COMM_WORLD, &send_requests[n] ); } _timeEnd = CycleTime(); level_f->cycles.interpolation_send += (_timeEnd-_timeStart); #endif // perform local interpolation... try and hide within Isend latency... _timeStart = CycleTime(); #pragma omp parallel for private(buffer) if(level_c->interpolation.num_blocks[1]>1) schedule(static,1) for(buffer=0;buffer<level_c->interpolation.num_blocks[1];buffer++){InterpolateBlock_PL(level_f,id_f,prescale_f,level_c,id_c,&level_c->interpolation.blocks[1][buffer]);} _timeEnd = CycleTime(); level_f->cycles.interpolation_local += (_timeEnd-_timeStart); // wait for MPI to finish... #ifdef USE_MPI _timeStart = CycleTime(); if(nMessages)MPI_Waitall(nMessages,level_f->interpolation.requests,level_f->interpolation.status); _timeEnd = CycleTime(); level_f->cycles.interpolation_wait += (_timeEnd-_timeStart); // unpack MPI receive buffers _timeStart = CycleTime(); #pragma omp parallel for private(buffer) if(level_f->interpolation.num_blocks[2]>1) schedule(static,1) for(buffer=0;buffer<level_f->interpolation.num_blocks[2];buffer++){IncrementBlock(level_f,id_f,prescale_f,&level_f->interpolation.blocks[2][buffer]);} _timeEnd = CycleTime(); level_f->cycles.interpolation_unpack += (_timeEnd-_timeStart); #endif level_f->cycles.interpolation_total += (uint64_t)(CycleTime()-_timeCommunicationStart); }
serial_tree_learner.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #define LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #include <LightGBM/dataset.h> #include <LightGBM/tree.h> #include <LightGBM/tree_learner.h> #include <LightGBM/utils/array_args.h> #include <LightGBM/utils/random.h> #include <string> #include <cmath> #include <cstdio> #include <memory> #include <random> #include <vector> #include "data_partition.hpp" #include "feature_histogram.hpp" #include "leaf_splits.hpp" #include "split_info.hpp" #ifdef USE_GPU // Use 4KBytes aligned allocator for ordered gradients and ordered hessians when GPU is enabled. // This is necessary to pin the two arrays in memory and make transferring faster. #include <boost/align/aligned_allocator.hpp> #endif using namespace json11; namespace LightGBM { /*! \brief forward declaration */ class CostEfficientGradientBoosting; /*! * \brief Used for learning a tree by single machine */ class SerialTreeLearner: public TreeLearner { public: friend CostEfficientGradientBoosting; explicit SerialTreeLearner(const Config* config); ~SerialTreeLearner(); void Init(const Dataset* train_data, bool is_constant_hessian) override; void ResetTrainingData(const Dataset* train_data) override; void ResetConfig(const Config* config) override; Tree* Train(const score_t* gradients, const score_t *hessians, bool is_constant_hessian, const Json& forced_split_json) override; Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override; Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred, const score_t* gradients, const score_t* hessians) override; void SetBaggingData(const data_size_t* used_indices, data_size_t num_data) override { data_partition_->SetUsedDataIndices(used_indices, num_data); } void AddPredictionToScore(const Tree* tree, double* out_score) const override { if (tree->num_leaves() <= 1) { return; } CHECK(tree->num_leaves() <= data_partition_->num_leaves()); #pragma omp parallel for schedule(static) for (int i = 0; i < tree->num_leaves(); ++i) { double output = static_cast<double>(tree->LeafOutput(i)); data_size_t cnt_leaf_data = 0; auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data); for (data_size_t j = 0; j < cnt_leaf_data; ++j) { out_score[tmp_idx[j]] += output; } } } void RenewTreeOutput(Tree* tree, const ObjectiveFunction* obj, std::function<double(const label_t*, int)> residual_getter, data_size_t total_num_data, const data_size_t* bag_indices, data_size_t bag_cnt) const override; bool IsHistColWise() const override { return is_hist_colwise_; } protected: void GetMultiValBin(const Dataset* dataset, bool is_first_time); virtual std::vector<int8_t> GetUsedFeatures(bool is_tree_level); /*! * \brief Some initial works before training */ virtual void BeforeTrain(); /*! * \brief Some initial works before FindBestSplit */ virtual bool BeforeFindBestSplit(const Tree* tree, int left_leaf, int right_leaf); virtual void FindBestSplits(); virtual void ConstructHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract); virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract); /*! * \brief Partition tree and data according best split. * \param tree Current tree, will be splitted on this function. * \param best_leaf The index of leaf that will be splitted. * \param left_leaf The index of left leaf after splitted. * \param right_leaf The index of right leaf after splitted. */ virtual void Split(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf); /* Force splits with forced_split_json dict and then return num splits forced.*/ virtual int32_t ForceSplits(Tree* tree, const Json& forced_split_json, int* left_leaf, int* right_leaf, int* cur_depth, bool *aborted_last_force_split); /*! * \brief Get the number of data in a leaf * \param leaf_idx The index of leaf * \return The number of data in the leaf_idx leaf */ inline virtual data_size_t GetGlobalDataCountInLeaf(int leaf_idx) const; /*! \brief number of data */ data_size_t num_data_; /*! \brief number of features */ int num_features_; /*! \brief training data */ const Dataset* train_data_; /*! \brief gradients of current iteration */ const score_t* gradients_; /*! \brief hessians of current iteration */ const score_t* hessians_; /*! \brief training data partition on leaves */ std::unique_ptr<DataPartition> data_partition_; /*! \brief used for generate used features */ Random random_; /*! \brief used for sub feature training, is_feature_used_[i] = false means don't used feature i */ std::vector<int8_t> is_feature_used_; /*! \brief used feature indices in current tree */ std::vector<int> used_feature_indices_; /*! \brief pointer to histograms array of parent of current leaves */ FeatureHistogram* parent_leaf_histogram_array_; /*! \brief pointer to histograms array of smaller leaf */ FeatureHistogram* smaller_leaf_histogram_array_; /*! \brief pointer to histograms array of larger leaf */ FeatureHistogram* larger_leaf_histogram_array_; /*! \brief store best split points for all leaves */ std::vector<SplitInfo> best_split_per_leaf_; /*! \brief store best split per feature for all leaves */ std::vector<SplitInfo> splits_per_leaf_; /*! \brief stores best thresholds for all feature for smaller leaf */ std::unique_ptr<LeafSplits> smaller_leaf_splits_; /*! \brief stores best thresholds for all feature for larger leaf */ std::unique_ptr<LeafSplits> larger_leaf_splits_; std::vector<int> valid_feature_indices_; #ifdef USE_GPU /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_; #else /*! \brief gradients of current iteration, ordered for cache optimized */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_hessians_; #endif /*! \brief is_data_in_leaf_[i] != 0 means i-th data is marked */ std::vector<char, Common::AlignmentAllocator<char, kAlignedSize>> is_data_in_leaf_; /*! \brief used to cache historical histogram to speed up*/ HistogramPool histogram_pool_; /*! \brief config of tree learner*/ const Config* config_; int num_threads_; std::vector<int> ordered_bin_indices_; bool is_constant_hessian_; std::unique_ptr<MultiValBin> multi_val_bin_; bool is_hist_colwise_; std::unique_ptr<CostEfficientGradientBoosting> cegb_; }; inline data_size_t SerialTreeLearner::GetGlobalDataCountInLeaf(int leaf_idx) const { if (leaf_idx >= 0) { return data_partition_->leaf_count(leaf_idx); } else { return 0; } } } // namespace LightGBM #endif // LightGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_
updater_basemaker-inl.h
/*! * Copyright 2014 by Contributors * \file updater_basemaker-inl.h * \brief implement a common tree constructor * \author Tianqi Chen */ #ifndef XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_ #define XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_ #include <rabit/rabit.h> #include <xgboost/base.h> #include <xgboost/tree_updater.h> #include <vector> #include <algorithm> #include <string> #include <limits> #include <utility> #include "./param.h" #include "../common/io.h" #include "../common/random.h" #include "../common/quantile.h" namespace xgboost { namespace tree { /*! * \brief base tree maker class that defines common operation * needed in tree making */ class BaseMaker: public TreeUpdater { public: void Init(const std::vector<std::pair<std::string, std::string> >& args) override { param_.InitAllowUnknown(args); } protected: // helper to collect and query feature meta information struct FMetaHelper { public: /*! \brief find type of each feature, use column format */ inline void InitByCol(DMatrix* p_fmat, const RegTree& tree) { fminmax_.resize(tree.param.num_feature * 2); std::fill(fminmax_.begin(), fminmax_.end(), -std::numeric_limits<bst_float>::max()); // start accumulating statistics for (const auto &batch : p_fmat->GetSortedColumnBatches()) { for (bst_uint fid = 0; fid < batch.Size(); ++fid) { auto c = batch[fid]; if (c.size() != 0) { fminmax_[fid * 2 + 0] = std::max(-c[0].fvalue, fminmax_[fid * 2 + 0]); fminmax_[fid * 2 + 1] = std::max(c[c.size() - 1].fvalue, fminmax_[fid * 2 + 1]); } } } } /*! \brief synchronize the information */ inline void SyncInfo() { rabit::Allreduce<rabit::op::Max>(dmlc::BeginPtr(fminmax_), fminmax_.size()); } // get feature type, 0:empty 1:binary 2:real inline int Type(bst_uint fid) const { CHECK_LT(fid * 2 + 1, fminmax_.size()) << "FeatHelper fid exceed query bound "; bst_float a = fminmax_[fid * 2]; bst_float b = fminmax_[fid * 2 + 1]; if (a == -std::numeric_limits<bst_float>::max()) return 0; if (-a == b) { return 1; } else { return 2; } } inline bst_float MaxValue(bst_uint fid) const { return fminmax_[fid *2 + 1]; } inline void SampleCol(float p, std::vector<bst_uint> *p_findex) const { std::vector<bst_uint> &findex = *p_findex; findex.clear(); for (size_t i = 0; i < fminmax_.size(); i += 2) { const auto fid = static_cast<bst_uint>(i / 2); if (this->Type(fid) != 0) findex.push_back(fid); } auto n = static_cast<unsigned>(p * findex.size()); std::shuffle(findex.begin(), findex.end(), common::GlobalRandom()); findex.resize(n); // sync the findex if it is subsample std::string s_cache; common::MemoryBufferStream fc(&s_cache); dmlc::Stream& fs = fc; if (rabit::GetRank() == 0) { fs.Write(findex); } rabit::Broadcast(&s_cache, 0); fs.Read(&findex); } private: std::vector<bst_float> fminmax_; }; // ------static helper functions ------ // helper function to get to next level of the tree /*! \brief this is helper function for row based data*/ inline static int NextLevel(const SparsePage::Inst &inst, const RegTree &tree, int nid) { const RegTree::Node &n = tree[nid]; bst_uint findex = n.SplitIndex(); for (const auto& ins : inst) { if (findex == ins.index) { if (ins.fvalue < n.SplitCond()) { return n.LeftChild(); } else { return n.RightChild(); } } } return n.DefaultChild(); } // ------class member helpers--------- /*! \brief initialize temp data structure */ inline void InitData(const std::vector<GradientPair> &gpair, const DMatrix &fmat, const RegTree &tree) { CHECK_EQ(tree.param.num_nodes, tree.param.num_roots) << "TreeMaker: can only grow new tree"; const std::vector<unsigned> &root_index = fmat.Info().root_index_; { // setup position position_.resize(gpair.size()); if (root_index.size() == 0) { std::fill(position_.begin(), position_.end(), 0); } else { for (size_t i = 0; i < position_.size(); ++i) { position_[i] = root_index[i]; CHECK_LT(root_index[i], (unsigned)tree.param.num_roots) << "root index exceed setting"; } } // mark delete for the deleted datas for (size_t i = 0; i < position_.size(); ++i) { if (gpair[i].GetHess() < 0.0f) position_[i] = ~position_[i]; } // mark subsample if (param_.subsample < 1.0f) { std::bernoulli_distribution coin_flip(param_.subsample); auto& rnd = common::GlobalRandom(); for (size_t i = 0; i < position_.size(); ++i) { if (gpair[i].GetHess() < 0.0f) continue; if (!coin_flip(rnd)) position_[i] = ~position_[i]; } } } { // expand query qexpand_.reserve(256); qexpand_.clear(); for (int i = 0; i < tree.param.num_roots; ++i) { qexpand_.push_back(i); } this->UpdateNode2WorkIndex(tree); } } /*! \brief update queue expand add in new leaves */ inline void UpdateQueueExpand(const RegTree &tree) { std::vector<int> newnodes; for (int nid : qexpand_) { if (!tree[nid].IsLeaf()) { newnodes.push_back(tree[nid].LeftChild()); newnodes.push_back(tree[nid].RightChild()); } } // use new nodes for qexpand qexpand_ = newnodes; this->UpdateNode2WorkIndex(tree); } // return decoded position inline int DecodePosition(bst_uint ridx) const { const int pid = position_[ridx]; return pid < 0 ? ~pid : pid; } // encode the encoded position value for ridx inline void SetEncodePosition(bst_uint ridx, int nid) { if (position_[ridx] < 0) { position_[ridx] = ~nid; } else { position_[ridx] = nid; } } /*! * \brief this is helper function uses column based data structure, * reset the positions to the lastest one * \param nodes the set of nodes that contains the split to be used * \param p_fmat feature matrix needed for tree construction * \param tree the regression tree structure */ inline void ResetPositionCol(const std::vector<int> &nodes, DMatrix *p_fmat, const RegTree &tree) { // set the positions in the nondefault this->SetNonDefaultPositionCol(nodes, p_fmat, tree); this->SetDefaultPostion(p_fmat, tree); } /*! * \brief helper function to set the non-leaf positions to default direction. * This function can be applied multiple times and will get the same result. * \param p_fmat feature matrix needed for tree construction * \param tree the regression tree structure */ inline void SetDefaultPostion(DMatrix *p_fmat, const RegTree &tree) { // set default direct nodes to default // for leaf nodes that are not fresh, mark then to ~nid, // so that they are ignored in future statistics collection const auto ndata = static_cast<bst_omp_uint>(p_fmat->Info().num_row_); #pragma omp parallel for schedule(static) for (bst_omp_uint ridx = 0; ridx < ndata; ++ridx) { const int nid = this->DecodePosition(ridx); if (tree[nid].IsLeaf()) { // mark finish when it is not a fresh leaf if (tree[nid].RightChild() == -1) { position_[ridx] = ~nid; } } else { // push to default branch if (tree[nid].DefaultLeft()) { this->SetEncodePosition(ridx, tree[nid].LeftChild()); } else { this->SetEncodePosition(ridx, tree[nid].RightChild()); } } } } /*! * \brief this is helper function uses column based data structure, * to CORRECT the positions of non-default directions that WAS set to default * before calling this function. * \param batch The column batch * \param sorted_split_set The set of index that contains split solutions. * \param tree the regression tree structure */ inline void CorrectNonDefaultPositionByBatch( const SparsePage &batch, const std::vector<bst_uint> &sorted_split_set, const RegTree &tree) { for (size_t fid = 0; fid < batch.Size(); ++fid) { auto col = batch[fid]; auto it = std::lower_bound(sorted_split_set.begin(), sorted_split_set.end(), fid); if (it != sorted_split_set.end() && *it == fid) { const auto ndata = static_cast<bst_omp_uint>(col.size()); #pragma omp parallel for schedule(static) for (bst_omp_uint j = 0; j < ndata; ++j) { const bst_uint ridx = col[j].index; const bst_float fvalue = col[j].fvalue; const int nid = this->DecodePosition(ridx); CHECK(tree[nid].IsLeaf()); int pid = tree[nid].Parent(); // go back to parent, correct those who are not default if (!tree[nid].IsRoot() && tree[pid].SplitIndex() == fid) { if (fvalue < tree[pid].SplitCond()) { this->SetEncodePosition(ridx, tree[pid].LeftChild()); } else { this->SetEncodePosition(ridx, tree[pid].RightChild()); } } } } } } /*! * \brief this is helper function uses column based data structure, * \param nodes the set of nodes that contains the split to be used * \param tree the regression tree structure * \param out_split_set The split index set */ inline void GetSplitSet(const std::vector<int> &nodes, const RegTree &tree, std::vector<unsigned>* out_split_set) { std::vector<unsigned>& fsplits = *out_split_set; fsplits.clear(); // step 1, classify the non-default data into right places for (int nid : nodes) { if (!tree[nid].IsLeaf()) { fsplits.push_back(tree[nid].SplitIndex()); } } std::sort(fsplits.begin(), fsplits.end()); fsplits.resize(std::unique(fsplits.begin(), fsplits.end()) - fsplits.begin()); } /*! * \brief this is helper function uses column based data structure, * update all positions into nondefault branch, if any, ignore the default branch * \param nodes the set of nodes that contains the split to be used * \param p_fmat feature matrix needed for tree construction * \param tree the regression tree structure */ virtual void SetNonDefaultPositionCol(const std::vector<int> &nodes, DMatrix *p_fmat, const RegTree &tree) { std::vector<unsigned> fsplits; this->GetSplitSet(nodes, tree, &fsplits); for (const auto &batch : p_fmat->GetSortedColumnBatches()) { for (auto fid : fsplits) { auto col = batch[fid]; const auto ndata = static_cast<bst_omp_uint>(col.size()); #pragma omp parallel for schedule(static) for (bst_omp_uint j = 0; j < ndata; ++j) { const bst_uint ridx = col[j].index; const bst_float fvalue = col[j].fvalue; const int nid = this->DecodePosition(ridx); // go back to parent, correct those who are not default if (!tree[nid].IsLeaf() && tree[nid].SplitIndex() == fid) { if (fvalue < tree[nid].SplitCond()) { this->SetEncodePosition(ridx, tree[nid].LeftChild()); } else { this->SetEncodePosition(ridx, tree[nid].RightChild()); } } } } } } /*! \brief helper function to get statistics from a tree */ template<typename TStats> inline void GetNodeStats(const std::vector<GradientPair> &gpair, const DMatrix &fmat, const RegTree &tree, std::vector< std::vector<TStats> > *p_thread_temp, std::vector<TStats> *p_node_stats) { std::vector< std::vector<TStats> > &thread_temp = *p_thread_temp; const MetaInfo &info = fmat.Info(); thread_temp.resize(omp_get_max_threads()); p_node_stats->resize(tree.param.num_nodes); #pragma omp parallel { const int tid = omp_get_thread_num(); thread_temp[tid].resize(tree.param.num_nodes, TStats()); for (unsigned int nid : qexpand_) { thread_temp[tid][nid] = TStats(); } } // setup position const auto ndata = static_cast<bst_omp_uint>(fmat.Info().num_row_); #pragma omp parallel for schedule(static) for (bst_omp_uint ridx = 0; ridx < ndata; ++ridx) { const int nid = position_[ridx]; const int tid = omp_get_thread_num(); if (nid >= 0) { thread_temp[tid][nid].Add(gpair[ridx]); } } // sum the per thread statistics together for (int nid : qexpand_) { TStats &s = (*p_node_stats)[nid]; s = TStats(); for (size_t tid = 0; tid < thread_temp.size(); ++tid) { s.Add(thread_temp[tid][nid]); } } } /*! \brief common helper data structure to build sketch */ struct SketchEntry { /*! \brief total sum of amount to be met */ double sum_total; /*! \brief statistics used in the sketch */ double rmin, wmin; /*! \brief last seen feature value */ bst_float last_fvalue; /*! \brief current size of sketch */ double next_goal; // pointer to the sketch to put things in common::WXQuantileSketch<bst_float, bst_float> *sketch; // initialize the space inline void Init(unsigned max_size) { next_goal = -1.0f; rmin = wmin = 0.0f; sketch->temp.Reserve(max_size + 1); sketch->temp.size = 0; } /*! * \brief push a new element to sketch * \param fvalue feature value, comes in sorted ascending order * \param w weight * \param max_size */ inline void Push(bst_float fvalue, bst_float w, unsigned max_size) { if (next_goal == -1.0f) { next_goal = 0.0f; last_fvalue = fvalue; wmin = w; return; } if (last_fvalue != fvalue) { double rmax = rmin + wmin; if (rmax >= next_goal && sketch->temp.size != max_size) { if (sketch->temp.size == 0 || last_fvalue > sketch->temp.data[sketch->temp.size-1].value) { // push to sketch sketch->temp.data[sketch->temp.size] = common::WXQuantileSketch<bst_float, bst_float>:: Entry(static_cast<bst_float>(rmin), static_cast<bst_float>(rmax), static_cast<bst_float>(wmin), last_fvalue); CHECK_LT(sketch->temp.size, max_size) << "invalid maximum size max_size=" << max_size << ", stemp.size" << sketch->temp.size; ++sketch->temp.size; } if (sketch->temp.size == max_size) { next_goal = sum_total * 2.0f + 1e-5f; } else { next_goal = static_cast<bst_float>(sketch->temp.size * sum_total / max_size); } } else { if (rmax >= next_goal) { LOG(TRACKER) << "INFO: rmax=" << rmax << ", sum_total=" << sum_total << ", naxt_goal=" << next_goal << ", size=" << sketch->temp.size; } } rmin = rmax; wmin = w; last_fvalue = fvalue; } else { wmin += w; } } /*! \brief push final unfinished value to the sketch */ inline void Finalize(unsigned max_size) { double rmax = rmin + wmin; if (sketch->temp.size == 0 || last_fvalue > sketch->temp.data[sketch->temp.size-1].value) { CHECK_LE(sketch->temp.size, max_size) << "Finalize: invalid maximum size, max_size=" << max_size << ", stemp.size=" << sketch->temp.size; // push to sketch sketch->temp.data[sketch->temp.size] = common::WXQuantileSketch<bst_float, bst_float>:: Entry(static_cast<bst_float>(rmin), static_cast<bst_float>(rmax), static_cast<bst_float>(wmin), last_fvalue); ++sketch->temp.size; } sketch->PushTemp(); } }; /*! \brief training parameter of tree grower */ TrainParam param_; /*! \brief queue of nodes to be expanded */ std::vector<int> qexpand_; /*! * \brief map active node to is working index offset in qexpand, * can be -1, which means the node is node actively expanding */ std::vector<int> node2workindex_; /*! * \brief position of each instance in the tree * can be negative, which means this position is no longer expanding * see also Decode/EncodePosition */ std::vector<int> position_; private: inline void UpdateNode2WorkIndex(const RegTree &tree) { // update the node2workindex std::fill(node2workindex_.begin(), node2workindex_.end(), -1); node2workindex_.resize(tree.param.num_nodes); for (size_t i = 0; i < qexpand_.size(); ++i) { node2workindex_[qexpand_[i]] = static_cast<int>(i); } } }; } // namespace tree } // namespace xgboost #endif // XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
convolution_sgemm.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void im2col_sgemm_rvv(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { #if __riscv_vector const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); #endif // Mat bottom_im2col(size, maxk, inch, 4u, 1, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; const float* bias = _bias; // permute Mat tmp; #if __riscv_vector if (size >= packn) tmp.create(packn * maxk, inch, size / packn + size % packn, 4u, 1, opt.workspace_allocator); else tmp.create(maxk, inch, size, 4u, 1, opt.workspace_allocator); { int nn_size = size / packn; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * packn; float* tmpptr = tmp.channel(i / packn); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { vse32_v_f32m1(tmpptr, vle32_v_f32m1(img0, vl), vl); img0 += size; tmpptr += packn; } } } int remain_size_start = nn_size * packn; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { float* tmpptr = tmp.channel(i / packn + i % packn); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; img0 += size; tmpptr += 1; } } } } #else // __riscv_vector tmp.create(maxk, inch, size, 4u, 1, opt.workspace_allocator); { #pragma omp parallel for num_threads(opt.num_threads) for (int i = 0; i < size; i++) { float* tmpptr = tmp.channel(i); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; img0 += size; tmpptr += 1; } } } } #endif // __riscv_vector #if __riscv_vector int nn_outch = outch >> 3; int remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* outptr0 = top_blob.channel(p); float* outptr1 = top_blob.channel(p + 1); float* outptr2 = top_blob.channel(p + 2); float* outptr3 = top_blob.channel(p + 3); float* outptr4 = top_blob.channel(p + 4); float* outptr5 = top_blob.channel(p + 5); float* outptr6 = top_blob.channel(p + 6); float* outptr7 = top_blob.channel(p + 7); const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const float* biasptr = bias ? bias + p : zeros; int i = 0; for (; i + (packn - 1) < size; i += packn) { const float* tmpptr = tmp.channel(i / packn); const float* kptr = kernel.channel(p / 8); int nn = inch * maxk; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(biasptr[0], vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(biasptr[1], vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(biasptr[2], vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(biasptr[3], vl); vfloat32m1_t _sum4 = vfmv_v_f_f32m1(biasptr[4], vl); vfloat32m1_t _sum5 = vfmv_v_f_f32m1(biasptr[5], vl); vfloat32m1_t _sum6 = vfmv_v_f_f32m1(biasptr[6], vl); vfloat32m1_t _sum7 = vfmv_v_f_f32m1(biasptr[7], vl); for (int q = 0; q < nn; q++) { vfloat32m1_t _val = vle32_v_f32m1(tmpptr, vl); _sum0 = vfmacc_vf_f32m1(_sum0, kptr[0], _val, vl); _sum1 = vfmacc_vf_f32m1(_sum1, kptr[1], _val, vl); _sum2 = vfmacc_vf_f32m1(_sum2, kptr[2], _val, vl); _sum3 = vfmacc_vf_f32m1(_sum3, kptr[3], _val, vl); _sum4 = vfmacc_vf_f32m1(_sum4, kptr[4], _val, vl); _sum5 = vfmacc_vf_f32m1(_sum5, kptr[5], _val, vl); _sum6 = vfmacc_vf_f32m1(_sum6, kptr[6], _val, vl); _sum7 = vfmacc_vf_f32m1(_sum7, kptr[7], _val, vl); tmpptr += packn; kptr += 8; } vse32_v_f32m1(outptr0, _sum0, vl); vse32_v_f32m1(outptr1, _sum1, vl); vse32_v_f32m1(outptr2, _sum2, vl); vse32_v_f32m1(outptr3, _sum3, vl); vse32_v_f32m1(outptr4, _sum4, vl); vse32_v_f32m1(outptr5, _sum5, vl); vse32_v_f32m1(outptr6, _sum6, vl); vse32_v_f32m1(outptr7, _sum7, vl); outptr0 += packn; outptr1 += packn; outptr2 += packn; outptr3 += packn; outptr4 += packn; outptr5 += packn; outptr6 += packn; outptr7 += packn; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / packn + i % packn); const float* kptr = kernel.channel(p / 8); int nn = inch * maxk; // inch always > 0 float sum0 = biasptr[0]; float sum1 = biasptr[1]; float sum2 = biasptr[2]; float sum3 = biasptr[3]; float sum4 = biasptr[4]; float sum5 = biasptr[5]; float sum6 = biasptr[6]; float sum7 = biasptr[7]; for (int q = 0; q < nn; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; sum4 += tmpptr[0] * kptr[4]; sum5 += tmpptr[0] * kptr[5]; sum6 += tmpptr[0] * kptr[6]; sum7 += tmpptr[0] * kptr[7]; tmpptr++; kptr += 8; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr4[0] = sum4; outptr5[0] = sum5; outptr6[0] = sum6; outptr7[0] = sum7; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* outptr0 = top_blob.channel(p); float* outptr1 = top_blob.channel(p + 1); float* outptr2 = top_blob.channel(p + 2); float* outptr3 = top_blob.channel(p + 3); const float zeros[4] = {0.f, 0.f, 0.f, 0.f}; const float* biasptr = bias ? bias + p : zeros; int i = 0; for (; i + (packn - 1) < size; i += packn) { const float* tmpptr = tmp.channel(i / packn); const float* kptr = kernel.channel(p / 8 + (p % 8) / 4); int nn = inch * maxk; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(biasptr[0], vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(biasptr[1], vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(biasptr[2], vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(biasptr[3], vl); for (int q = 0; q < nn; q++) { vfloat32m1_t _val = vle32_v_f32m1(tmpptr, vl); _sum0 = vfmacc_vf_f32m1(_sum0, kptr[0], _val, vl); _sum1 = vfmacc_vf_f32m1(_sum1, kptr[1], _val, vl); _sum2 = vfmacc_vf_f32m1(_sum2, kptr[2], _val, vl); _sum3 = vfmacc_vf_f32m1(_sum3, kptr[3], _val, vl); tmpptr += packn; kptr += 4; } vse32_v_f32m1(outptr0, _sum0, vl); vse32_v_f32m1(outptr1, _sum1, vl); vse32_v_f32m1(outptr2, _sum2, vl); vse32_v_f32m1(outptr3, _sum3, vl); outptr0 += packn; outptr1 += packn; outptr2 += packn; outptr3 += packn; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / packn + i % packn); const float* kptr = kernel.channel(p / 8 + (p % 8) / 4); int nn = inch * maxk; // inch always > 0 float sum0 = biasptr[0]; float sum1 = biasptr[1]; float sum2 = biasptr[2]; float sum3 = biasptr[3]; for (int q = 0; q < nn; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* outptr0 = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; int i = 0; for (; i + (packn - 1) < size; i += packn) { const float* tmpptr = tmp.channel(i / packn); const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4); int nn = inch * maxk; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(bias0, vl); for (int q = 0; q < nn; q++) { _sum0 = vfmacc_vf_f32m1(_sum0, kptr[0], vle32_v_f32m1(tmpptr, vl), vl); tmpptr += packn; kptr++; } vse32_v_f32m1(outptr0, _sum0, vl); outptr0 += packn; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / packn + i % packn); const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; for (int q = 0; q < nn; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } #else // __riscv_vector #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr0 = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; for (int i = 0; i < size; i++) { const float* tmpptr = tmp.channel(i); const float* kptr = kernel.channel(p); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; for (int q = 0; q < nn; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } #endif // __riscv_vector } static void convolution_im2col_sgemm_transform_kernel_rvv(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = 8b-maxk-inch-outch/8b Mat kernel = _kernel.reshape(maxk, inch, outch); #if __riscv_vector kernel_tm.create(8 * maxk, inch, outch / 8 + (outch % 8) / 4 + outch % 4); int q = 0; for (; q + 7 < outch; q += 8) { const Mat k0 = kernel.channel(q); const Mat k1 = kernel.channel(q + 1); const Mat k2 = kernel.channel(q + 2); const Mat k3 = kernel.channel(q + 3); const Mat k4 = kernel.channel(q + 4); const Mat k5 = kernel.channel(q + 5); const Mat k6 = kernel.channel(q + 6); const Mat k7 = kernel.channel(q + 7); float* g00 = kernel_tm.channel(q / 8); for (int p = 0; p < inch; p++) { const float* k00 = k0.row(p); const float* k10 = k1.row(p); const float* k20 = k2.row(p); const float* k30 = k3.row(p); const float* k40 = k4.row(p); const float* k50 = k5.row(p); const float* k60 = k6.row(p); const float* k70 = k7.row(p); for (int k = 0; k < maxk; k++) { g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k40[k]; g00[5] = k50[k]; g00[6] = k60[k]; g00[7] = k70[k]; g00 += 8; } } } for (; q + 3 < outch; q += 4) { const Mat k0 = kernel.channel(q); const Mat k1 = kernel.channel(q + 1); const Mat k2 = kernel.channel(q + 2); const Mat k3 = kernel.channel(q + 3); float* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4); for (int p = 0; p < inch; p++) { const float* k00 = k0.row(p); const float* k10 = k1.row(p); const float* k20 = k2.row(p); const float* k30 = k3.row(p); for (int k = 0; k < maxk; k++) { g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00 += 4; } } } for (; q < outch; q++) { const Mat k0 = kernel.channel(q); float* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4 + q % 4); for (int p = 0; p < inch; p++) { const float* k00 = k0.row(p); for (int k = 0; k < maxk; k++) { g00[0] = k00[k]; g00 += 1; } } } #else kernel_tm = kernel; #endif // __riscv_vector } static void convolution_im2col_sgemm_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 4u, 1, opt.workspace_allocator); { const int gap = w * stride_h - outw * stride_w; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); float* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const float* sptr = img.row<const float>(dilation_h * u) + dilation_w * v; for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { ptr[0] = sptr[0]; sptr += stride_w; ptr += 1; } sptr += gap; } } } } } im2col_sgemm_rvv(bottom_im2col, top_blob, kernel, _bias, opt); }
GB_unop__ceil_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__ceil_fc64_fc64 // op(A') function: GB_unop_tran__ceil_fc64_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_cceil (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_cceil (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = GB_cceil (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CEIL || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__ceil_fc64_fc64 ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_cceil (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_cceil (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__ceil_fc64_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
kmercount.h
#ifndef BELLA_KMERCOUNT_H_ #define BELLA_KMERCOUNT_H_ #include <iostream> #include <cstdio> #include <cstdlib> #include <fstream> #include <istream> #include <vector> #include <string> #include <stdlib.h> #include <algorithm> #include <utility> #include <array> #include <tuple> #include <queue> #include <memory> #include <stack> #include <numeric> #include <functional> #include <cstring> #include <string.h> #include <math.h> #include <cassert> #include <ios> #include <sys/stat.h> #include <sys/types.h> #include <sys/sysctl.h> #include <map> #include <unordered_map> #include <omp.h> #include <fstream> #include <typeinfo> #ifdef __NVCC__ #include "loganGPU/logan.cuh" #endif #include "libcuckoo/cuckoohash_map.hh" #include "libbloom/bloom64.h" #include "kmercode/hash_funcs.h" #include "kmercode/Kmer.hpp" #include "kmercode/Buffer.h" #include "kmercode/common.h" #include "kmercode/fq_reader.h" #include "kmercode/ParallelFASTQ.h" #include "kmercode/bound.hpp" #include "kmercode/hyperloglog.hpp" #include "mtspgemm2017/common.h" using namespace std; #define ASCIIBASE 33 // Pacbio quality score ASCII BASE #ifndef PRINT #define PRINT #endif template <typename IT> using CuckooDict = cuckoohash_map<Kmer, IT>; // GG: when couting k-mers the values can be 16bit (k-mer occurrence) instead of 32 (k-mer ids in the final dictionary) typedef cuckoohash_map<Kmer, unsigned short int> dictionary_t_16bit; // <k-mer && reverse-complement, kmer_multiplicity> struct filedata { char filename[MAX_FILE_PATH]; size_t filesize; }; /** * @brief GetFiles * @param filename * @return */ vector<filedata> GetFiles(char *filename) { int64_t totalsize = 0; int numfiles = 0; std::vector<filedata> filesview; filedata fdata; ifstream allfiles(filename); if(!allfiles.is_open()) { std::string someString(filename); std::string ErrorMessage = "Could not open " + someString; printLog(ErrorMessage); exit(1); } allfiles.getline(fdata.filename, MAX_FILE_PATH); while(!allfiles.eof()) { struct stat st; stat(fdata.filename, &st); fdata.filesize = st.st_size; filesview.push_back(fdata); std::string InputFile = filesview.back().filename; std::string str1 = std::to_string((float)filesview.back().filesize / (1024*1024)); std::string str2 = " MB"; std::string InputSize = str1 + str2; printLog(InputFile); printLog(InputSize); allfiles.getline(fdata.filename, MAX_FILE_PATH); totalsize += fdata.filesize; numfiles++; } return filesview; } /** * @brief SimpleCount * @param allfiles * @param countsreliable_denovo * @param LowerBound * @param UpperBound * @param b_pars.kmerSize * @param upperlimit */ template <typename IT> void SimpleCount(vector<filedata> & allfiles, CuckooDict<IT> & countsreliable_denovo, int& LowerBound, int& UpperBound, int coverage, size_t upperlimit, BELLApars & b_pars) { vector < vector<double> > allquals(MAXTHREADS); double denovocount = omp_get_wtime(); size_t totreads = 0; dictionary_t_16bit countsdenovo; auto updatefn = [](unsigned short int &count) { if (count < std::numeric_limits<unsigned short int>::max()) ++count; }; for(auto itr=allfiles.begin(); itr!=allfiles.end(); itr++) { #pragma omp parallel { ParallelFASTQ *pfq = new ParallelFASTQ(); pfq->open(itr->filename, false, itr->filesize); if(MYTHREAD == 0) { const char* ReadingFASTQ = itr->filename; printLog(ReadingFASTQ); } vector<string> seqs; vector<string> quals; vector<string> nametags; size_t tlreads = 0; // thread local reads size_t fillstatus = 1; while(fillstatus) { fillstatus = pfq->fill_block(nametags, seqs, quals, upperlimit); size_t nreads = seqs.size(); for(int i=0; i<nreads; i++) { // remember that the last valid position is length()-1 int len = seqs[i].length(); double rerror = 0.0; for(int j = 0; j<= len - b_pars.kmerSize; j++) { std::string kmerstrfromfastq = seqs[i].substr(j, b_pars.kmerSize); Kmer mykmer(kmerstrfromfastq.c_str(), kmerstrfromfastq.length()); Kmer lexsmall = mykmer.rep(); countsdenovo.upsert(lexsmall, updatefn, 1); if(b_pars.skipEstimate == false) { // accuracy int bqual = (int)quals[i][j] - ASCIIBASE; double berror = pow(10,-(double)bqual/10); rerror += berror; } } if(b_pars.skipEstimate == false) { // remaining k qual position accuracy for(int j = len - b_pars.kmerSize + 1; j < len; j++) { int bqual = (int)quals[i][j] - ASCIIBASE; double berror = pow(10,-(double)bqual/10); rerror += berror; } rerror = rerror / len; allquals[MYTHREAD].push_back(rerror); } } // for(int i=0; i<nreads; i++) tlreads += nreads; } //while(fillstatus) delete pfq; #pragma omp critical { totreads += tlreads; } } } // Error estimation double& errorRate = b_pars.errorRate; if(b_pars.skipEstimate == false) { errorRate = 0.0; // reset to 0 here, otherwise it cointains default or user-defined values #pragma omp for reduction(+:errorRate) for (int i = 0; i < MAXTHREADS; i++) { double temp = std::accumulate(allquals[i].begin(), allquals[i].end(), 0.0); errorRate += temp / (double)allquals[i].size(); } b_pars.errorRate = errorRate / (double)MAXTHREADS; } double load2kmers = omp_get_wtime(); std::string kmerCountingTime = std::to_string(load2kmers - denovocount) + " seconds"; printLog(kmerCountingTime); // Reliable bounds computation using estimated error rate from phred quality score LowerBound = computeLower(coverage, b_pars.errorRate, b_pars.kmerSize, b_pars.minProbability); UpperBound = computeUpper(coverage, b_pars.errorRate, b_pars.kmerSize, b_pars.minProbability); // Reliable k-mer filter on countsdenovo IT kmer_id_denovo = 0; auto lt = countsdenovo.lock_table(); // our counting for (const auto &it : lt) if (it.second >= LowerBound && it.second <= UpperBound) { countsreliable_denovo.insert(it.first, kmer_id_denovo); ++kmer_id_denovo; } lt.unlock(); // unlock the table // Print some information about the table if (countsreliable_denovo.size() == 0) { std::string ErrorMessage = "BELLA terminated: 0 entries within reliable range. You may want to reduce the k-mer lenght."; printLog(ErrorMessage); exit(1); } else { size_t numReliableKmers = countsreliable_denovo.size(); printLog(numReliableKmers); } countsdenovo.clear(); // free } /** * @brief DeNovoCount * @param allfiles * @param countsreliable_denovo * @param LowerBound * @param UpperBound * @param b_pars.kmerSize * @param upperlimit */ template <typename IT> void DeNovoCount(vector<filedata> & allfiles, CuckooDict<IT> & countsreliable_denovo, int& LowerBound, int& UpperBound, int coverage, size_t upperlimit, BELLApars & b_pars) { vector < vector<Kmer> > allkmers(MAXTHREADS); vector < vector<double> > allquals(MAXTHREADS); vector < HyperLogLog > hlls(MAXTHREADS, HyperLogLog(12)); // std::vector fill constructor double denovocount = omp_get_wtime(); double CardinalityEstimate; size_t totreads = 0; for(auto itr=allfiles.begin(); itr!=allfiles.end(); itr++) { #pragma omp parallel { ParallelFASTQ *pfq = new ParallelFASTQ(); pfq->open(itr->filename, false, itr->filesize); if(MYTHREAD == 0) { const char* ReadingFASTQ = itr->filename; printLog(ReadingFASTQ); } vector<string> seqs; vector<string> quals; vector<string> nametags; size_t tlreads = 0; // thread local reads size_t fillstatus = 1; while(fillstatus) { fillstatus = pfq->fill_block(nametags, seqs, quals, upperlimit); size_t nreads = seqs.size(); for(int i=0; i<nreads; i++) { // remember that the last valid position is length()-1 int len = seqs[i].length(); double rerror = 0.0; for(int j = 0; j<= len - b_pars.kmerSize; j++) { std::string kmerstrfromfastq = seqs[i].substr(j, b_pars.kmerSize); Kmer mykmer(kmerstrfromfastq.c_str(), kmerstrfromfastq.length()); Kmer lexsmall = mykmer.rep(); allkmers[MYTHREAD].push_back(lexsmall); hlls[MYTHREAD].add((const char*) lexsmall.getBytes(), lexsmall.getNumBytes()); if(b_pars.skipEstimate == false) { // accuracy int bqual = (int)quals[i][j] - ASCIIBASE; double berror = pow(10,-(double)bqual/10); rerror += berror; } } if(b_pars.skipEstimate == false) { // remaining k qual position accuracy for(int j = len - b_pars.kmerSize + 1; j < len; j++) { int bqual = (int)quals[i][j] - ASCIIBASE; double berror = pow(10,-(double)bqual/10); rerror += berror; } rerror = rerror / len; allquals[MYTHREAD].push_back(rerror); } } // for(int i=0; i<nreads; i++) tlreads += nreads; } //while(fillstatus) delete pfq; #pragma omp critical { totreads += tlreads; } } } // Error estimation double& errorRate = b_pars.errorRate; if(b_pars.skipEstimate == false) { errorRate = 0.0; // reset to 0 here, otherwise it cointains default or user-defined values #pragma omp for reduction(+:errorRate) for (int i = 0; i < MAXTHREADS; i++) { double temp = std::accumulate(allquals[i].begin(), allquals[i].end(), 0.0); errorRate += temp / (double)allquals[i].size(); } b_pars.errorRate = errorRate / (double)MAXTHREADS; } // HLL reduction (serial for now) to avoid double iteration for (int i = 1; i < MAXTHREADS; i++) { std::transform(hlls[0].M.begin(), hlls[0].M.end(), hlls[i].M.begin(), hlls[0].M.begin(), [](uint8_t c1, uint8_t c2) -> uint8_t{ return std::max(c1, c2); }); } CardinalityEstimate = hlls[0].estimate(); double load2kmers = omp_get_wtime(); std::string kmerCountingTime = std::to_string(load2kmers - denovocount) + " seconds"; printLog(kmerCountingTime); const double desired_probability_of_false_positive = 0.05; struct bloom * bm = (struct bloom*) malloc(sizeof(struct bloom)); bloom_init64(bm, CardinalityEstimate * 1.1, desired_probability_of_false_positive); double TableSize = ((double)bm->bits)/8/1024/1024; int numHashFunctions = bm->hashes; printLog(CardinalityEstimate); printLog(TableSize); printLog(numHashFunctions); dictionary_t_16bit countsdenovo; #pragma omp parallel { for(auto v:allkmers[MYTHREAD]) { bool inBloom = (bool) bloom_check_add(bm, v.getBytes(), v.getNumBytes(),1); if(inBloom) countsdenovo.insert(v, 0); } } double firstpass = omp_get_wtime(); std::string FirstKmerPassTime = std::to_string(firstpass - load2kmers) + " seconds"; printLog(FirstKmerPassTime); free(bm); // release bloom filter memory // in this pass, only use entries that already are in the hash table auto updatecount = [](unsigned short int &num) { ++num; }; #pragma omp parallel { for(auto v:allkmers[MYTHREAD]) { // does nothing if the entry doesn't exist in the table countsdenovo.update_fn(v, updatecount); } } std::string SecondKmerPassTime = std::to_string(omp_get_wtime() - firstpass) + " seconds"; printLog(SecondKmerPassTime); // Reliable bounds computation using estimated error rate from phred quality score LowerBound = computeLower(coverage, b_pars.errorRate, b_pars.kmerSize, b_pars.minProbability); UpperBound = computeUpper(coverage, b_pars.errorRate, b_pars.kmerSize, b_pars.minProbability); // Reliable k-mer filter on countsdenovo IT kmer_id_denovo = 0; auto lt = countsdenovo.lock_table(); // our counting for (const auto &it : lt) if (it.second >= LowerBound && it.second <= UpperBound) { countsreliable_denovo.insert(it.first, kmer_id_denovo); ++kmer_id_denovo; } lt.unlock(); // unlock the table // Print some information about the table if (countsreliable_denovo.size() == 0) { std::string ErrorMessage = "BELLA terminated: 0 entries within reliable range. You may want to reduce the k-mer lenght."; printLog(ErrorMessage); exit(1); } else { size_t numReliableKmers = countsreliable_denovo.size(); printLog(numReliableKmers); } countsdenovo.clear(); // free } // Returns the new average after including x double getAvg(double prev_avg, double x, int64_t n) { return (prev_avg * n + x) / (n + 1); } /** * @brief Split4Count * @param allfiles * @param countsreliable_denovo * @param LowerBound * @param UpperBound * @param b_pars.kmerSize * @param upperlimit */ template <typename IT> void SplitCount(vector<filedata> & allfiles, CuckooDict<IT> & countsreliable_denovo, int& LowerBound, int& UpperBound, int coverage, size_t upperlimit, BELLApars & b_pars) { size_t totreads = 0; size_t totbases = 0; double avesofar = 0.0; // Reliable k-mer filter on countsdenovo IT kmer_id_denovo = 0; for(int CurrSplitCount = 0; CurrSplitCount < b_pars.SplitCount; ++CurrSplitCount) // b_pars.SplitCount { double denovocount = omp_get_wtime(); vector < vector<Kmer> > allkmers(MAXTHREADS); vector < HyperLogLog > hlls(MAXTHREADS, HyperLogLog(12)); // std::vector fill constructor for(auto itr=allfiles.begin(); itr!=allfiles.end(); itr++) { #pragma omp parallel { ParallelFASTQ *pfq = new ParallelFASTQ(); pfq->open(itr->filename, false, itr->filesize); if(MYTHREAD == 0) { const char* ReadingFASTQ = itr->filename; printLog(ReadingFASTQ); } vector<string> seqs; vector<string> quals; vector<string> nametags; size_t tlreads = 0; // thread local reads size_t tlbases = 0; // thread local bases double tlave = 0.0; // thread local error rate average size_t fillstatus = 1; while(fillstatus) { fillstatus = pfq->fill_block(nametags, seqs, quals, upperlimit); size_t nreads = seqs.size(); for(int i = 0; i < nreads; i++) { // remember that the last valid position is length()-1 int len = seqs[i].length(); double rerror = 0.0; for(int j = 0; j<= len - b_pars.kmerSize; j++) { std::string kmerstrfromfastq = seqs[i].substr(j, b_pars.kmerSize); Kmer mykmer(kmerstrfromfastq.c_str(), kmerstrfromfastq.length()); Kmer lexsmall = mykmer.rep(); if(lexsmall.hash() % b_pars.SplitCount == CurrSplitCount) // mod b_pars.SplitCount { allkmers[MYTHREAD].push_back(lexsmall); hlls[MYTHREAD].add((const char*) lexsmall.getBytes(), lexsmall.getNumBytes()); } if(CurrSplitCount == 0 && b_pars.skipEstimate == false) { // accuracy int bqual = (int)quals[i][j] - ASCIIBASE; double berror = pow(10,-(double)bqual/10); tlave = getAvg(tlave, berror, tlbases++); } } if(CurrSplitCount == 0 && b_pars.skipEstimate == false) { // remaining k qual position accuracy for(int j = len - b_pars.kmerSize + 1; j < len; j++) { int bqual = (int)quals[i][j] - ASCIIBASE; double berror = pow(10,-(double)bqual/10); tlave = getAvg(tlave, berror, tlbases++); } } } // for(int i=0; i<nreads; i++) tlreads += nreads; } //while(fillstatus) delete pfq; if(CurrSplitCount == 0) // don't overcount by a factor of b_pars.SplitCount { #pragma omp critical { totreads += tlreads; avesofar = (avesofar * totbases + tlave * tlbases) / (totbases + tlbases); totbases += tlbases; } } } // #pragma omp parallel } // for allfiles if(CurrSplitCount == 0) { if(b_pars.skipEstimate == false) { b_pars.errorRate = avesofar; printLog(b_pars.errorRate); } // Reliable bounds computation using estimated error rate from phred quality score LowerBound = computeLower(coverage, b_pars.errorRate, b_pars.kmerSize, b_pars.minProbability); UpperBound = computeUpper(coverage, b_pars.errorRate, b_pars.kmerSize, b_pars.minProbability); printLog(LowerBound); printLog(UpperBound); } // HLL reduction (serial for now) to avoid double iteration for (int i = 1; i < MAXTHREADS; i++) { std::transform(hlls[0].M.begin(), hlls[0].M.end(), hlls[i].M.begin(), hlls[0].M.begin(), [](uint8_t c1, uint8_t c2) -> uint8_t{ return std::max(c1, c2); }); } double CardinalityEstimate = hlls[0].estimate(); double load2kmers = omp_get_wtime(); std::string kmerCountingTime = std::to_string(load2kmers - denovocount) + " seconds"; printLog(kmerCountingTime); const double desired_probability_of_false_positive = 0.05; struct bloom * bm = (struct bloom*) malloc(sizeof(struct bloom)); bloom_init64(bm, CardinalityEstimate * 1.1, desired_probability_of_false_positive); double TableSize = ((double)bm->bits)/8/1024/1024; int numHashFunctions = bm->hashes; printLog(CardinalityEstimate); printLog(TableSize); printLog(numHashFunctions); dictionary_t_16bit countsdenovo; #pragma omp parallel { for(auto v:allkmers[MYTHREAD]) { bool inBloom = (bool) bloom_check_add(bm, v.getBytes(), v.getNumBytes(),1); if(inBloom) countsdenovo.insert(v, 0); } } size_t tot_kmers = 0; for (int i=0; i<MAXTHREADS; i++) tot_kmers+= allkmers[i].size(); printLog(CurrSplitCount); std::string TotalKmers = std::to_string(tot_kmers); printLog(TotalKmers); double firstpass = omp_get_wtime(); std::string FirstKmerPassTime = std::to_string(firstpass - load2kmers) + " seconds"; printLog(FirstKmerPassTime); free(bm); // release bloom filter memory // in this pass, only use entries that already are in the hash table auto updatecount = [](unsigned short int &num) { ++num; }; #pragma omp parallel { for(auto v:allkmers[MYTHREAD]) { // does nothing if the entry doesn't exist in the table countsdenovo.update_fn(v, updatecount); } } std::string SecondKmerPassTime = std::to_string(omp_get_wtime() - firstpass) + " seconds"; printLog(SecondKmerPassTime); auto lt = countsdenovo.lock_table(); // our counting for (const auto &it : lt) { if (it.second >= LowerBound && it.second <= UpperBound) { countsreliable_denovo.insert(it.first, kmer_id_denovo); ++kmer_id_denovo; } } lt.unlock(); // unlock the table // Print some information about the table if (countsreliable_denovo.size() == 0) { std::string ErrorMessage = "BELLA terminated: 0 entries within reliable range. You may want to reduce the k-mer lenght."; printLog(ErrorMessage); exit(1); } else { size_t numReliableKmers = countsreliable_denovo.size(); printLog(numReliableKmers); } countsdenovo.clear(); // free } // for all b_pars.SplitCount } #endif
bucle-for.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #define omp_get_num_threads() 1 #endif int main(int argc, char ** argv) { int i, n = 9; if(argc < 2) { fprintf(stderr,"\n[ERROR] - Falta nº iteraciones \n"); exit(-1); } n = atoi(argv[1]); #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) printf("thread %d ejecuta la iteración %d del bucle\n",omp_get_thread_num(),i); } return(0); }